Autofac - global callback on object resolution

How can I register a global callback in an Autofac container that runs whenever an object resolves?

I want to use reflection and check if the object has a method with a name Initialize()and calls it if it does. I want him to be duck, i.e. No interfaces required.

Thank!

+5
source share
1 answer

In Autofac, you can use the interface IComponentRegistrationto subscribe to various life events:

  • Onactivating
  • Onactivated
  • Onrelease

You can get an instance IComponentRegistrationby creating Moduleand overriding the method AttachToComponentRegistration:

public class EventModule : Module
{
    protected override void AttachToComponentRegistration(
        IComponentRegistry componentRegistry, 
        IComponentRegistration registration)
    {
        registration.Activated += OnActivated;
    }

    private void OnActivated(object sender, ActivatedEventArgs<object> e)
    {
        e.Instance.GetType().GetMethod("Initialize").Invoke(e.Instance, null);
    }
}

:

var builder = new ContainerBuilder();
builder.RegisterModule<EventModule>();

OnActivated , , .

+12

All Articles