user593358
user593358

Reputation:

Autofac: Add OnActivated to all registrations

I need to add .OnActivated(Initialize) to all registrations. Below is how I do this now:

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

It would be great if I could simplify it to something like:

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

Is something similar possible?

Thanks

Upvotes: 5

Views: 1480

Answers (1)

Jim Bolla
Jim Bolla

Reputation: 8295

You could create your own extension method like so:

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

and then you can register like this:

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

Upvotes: 6

Related Questions