Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofac - global callback when object resolved

Tags:

autofac

How can I register global callback on Autofac container which is triggered whenever any object is resolved?

I want to use reflection and check if an object has a method called Initialize() and call it if it does. I want it to be duck typed i.e. no interfaces are required.

Thanks!

like image 544
Konstantin Spirin Avatar asked Jul 26 '12 05:07

Konstantin Spirin


1 Answers

In Autofac you can use the IComponentRegistration interface to subscribe on various lifetime events:

  • OnActivating
  • OnActivated
  • OnRelease

You can get the IComponentRegistration instance by creating a Module and override the AttachToComponentRegistration method:

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);
    }
}

Now you only need to register your module in your container builder:

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

and the OnActivated method will be called after every component activation no mater in which module you have registered the component.

like image 160
nemesv Avatar answered Oct 15 '22 11:10

nemesv