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!
In Autofac you can use the IComponentRegistration
interface to subscribe on various lifetime events:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With