Autofac:将OnActivated添加到所有注册

时间:2011-05-18 17:42:18

标签: c# autofac

我需要在所有注册中添加.OnActivated(Initialize)。以下是我现在的处理方式:

builder.RegisterType<A>()
    .OnActivated(Initialize);

builder.RegisterType<B>()
    .OnActivated(Initialize);

builder.RegisterType<C>()
    .OnActivated(Initialize);

void Initialize(IActivatedEventArgs<object> context)
{
    object obj = context.Instance;
    if (obj is IHasPostConstructor)        
        (obj as IHasPostConstructor).PostConstructor();        
}

如果我能将它简化为类似的东西,那就太好了。

builder.RegisterType<A>();
builder.RegisterType<B>();
builder.RegisterType<C>();
builder.AllRegistrations.OnActivated(Initialize);

类似的东西可能吗?

由于

1 个答案:

答案 0 :(得分:6)

您可以像这样创建自己的扩展方法:

public static IRegistrationBuilder<T, ConcreteReflectionActivatorData, SingleRegistrationStyle>  RegisterWithInit<T>(this ContainerBuilder builder)
{
    return builder.RegisterType<T>.OnActivated(Initialize);
}

然后你可以这样注册:

builder.RegisterWithInit<A>();
builder.RegisterWithInit<B>();
builder.RegisterWithInit<C>();