7

如何在 Autofac 容器上注册全局回调,该回调在任何对象被解析时触发?

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

谢谢!

4

1 回答 1

15

在 Autofac 中,您可以使用该IComponentRegistration接口订阅各种生命周期事件:

  • 激活时
  • 已激活
  • 发布时

您可以IComponentRegistration通过创建Module并覆盖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无论您在哪个模块中注册了该组件,每次激活组件后都会调用该方法。

于 2012-07-26T06:07:29.920 回答