Autofac-解析对象时的全局回调



如何在Autofac容器上注册全局回调,每当解析任何对象时都会触发全局回调?

我想使用反射,检查对象是否有一个名为Initialize()的方法,如果有,就调用它。我希望它是鸭子类型的,即不需要接口。

谢谢!

在Autofac中,您可以使用IComponentRegistration接口订阅各种终身事件:

  • OnActivating
  • OnActivated
  • OnRelease

您可以通过创建Module并覆盖AttachToComponentRegistration方法来获得IComponentRegistration实例:

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

并且无论您在哪个模块中注册了组件,每次组件激活后都会调用CCD_ 6方法。

最新更新