Reputation: 471
I would like to use autofac IoC to initialize my service that injected into MVC controller constructor. Assume service interface looks like this:
public interface IService
{
void SetValidationContainer(IReadOnlyDictionary<string, ModelStateEntry> validations);
}
And controller ctor:
public class HelloWorldController : Controller
{
private readonly IService _service;
public HelloWorldController(IService service)
{
_service = service;
_service.SetValidationContainer(ModelState);
}
}
Is it possible to move calling "SetValidationContainer(ModelState)" to DI config? And use something like this:
container.Register<IService>
.As<ServiceImplementaion>
.AfterInjectedInto<Controller>
.Call(service, controller => service.SetValidationContainer(controller.ModelState));
Upvotes: 0
Views: 1404
Reputation: 16192
Autofac provides 3 events.
OnActivating
: raised before a component is used OnActivated
: raised once a component is fully constructedOnRelease
: raised when a component is disposedIn your case, you could use the OnActivated
to initialize your component.
builder.RegisterType<Service>()
.As<IService>()
.OnActivating(e => e.Instance.Initialize());
Have a look at Autofac Lifetime Events documentation for more information
Upvotes: 2