2012-07-26 48 views

回答

12

在Autofac可以使用IComponentRegistration接口订阅各种一生的事件:

  • OnActivating
  • OnActivated
  • OnRelease

您可以通过创建一个Module得到IComponentRegistration实例并覆盖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方法将每个组件激活没有母校在哪个模块已注册的组件后调用。