malonowa
malonowa

Reputation: 471

Initialize service in controller constructor

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

Answers (1)

Cyril Durand
Cyril Durand

Reputation: 16192

Autofac provides 3 events.

  • OnActivating : raised before a component is used
  • OnActivated : raised once a component is fully constructed
  • OnRelease : raised when a component is disposed

In 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

Related Questions