Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject instance via Controller Factory

I'm studying about Dependency Injection, and I need some help to a better understand about Controller Factory.

enter image description here

I need inject the SqlReceitaRepository via Constructor Injection in HomeController.

HomeController Constructor

private readonly IReceitaRepository repositorio;

public HomeController(IReceitaRepository repositorio)
{
    if (repositorio == null)
       throw new ArgumentException("repositorio");

    this.repositorio = repositorio;
}

With SqlReceitaRepository implemented, I can now set up ASP.NET MVC to inject an instance of it into instances of HomeController, but how can I do that ?

Detail: I'm using NHibernate instead Entity Framework.

If needed, the classes that will be created for accomplish this, will belong which layer ?

I read some articles and I saw that I need put a new line in my Global.asax

Global.asax

var controllerFactory = new ReceitaControllerFactory();
ControllerBuilder.Current.SetControllerFactory(controllerFactory);

I'm assuming that ReceitaControllerFactory should contain the IControllerFactory implementation.

But looking at the IControllerFactory

public interface IControllerFactory
{
    IController CreateController(RequestContext requestContext, string controllerName);
    SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName);
    void ReleaseController(IController controller);
}

We can see the method CreateController, but how can I inject a instance of SqlReceitaRepository into HomeController's instance?

like image 679
Lucas_Santos Avatar asked Nov 22 '25 19:11

Lucas_Santos


1 Answers

The simple answer:

IController CreateController(RequestContext requestContext, string controllerName)
{
    return new HomeController(new SqlReceitaRepository());
}

But, as you might have noticed, this will only work for one controller type as it is written. More importantly, it's not very maintainable. So the right answer is to get a popular DI framework like Ninject, and get the plugins you need for your frameworks (Ninject MVC, e.g.), and then define your bindings and let the framework take care of figuring out the dependencies:

Bind<IReceitaRepository>().To<SqlReceitaRepository>();
like image 198
StriplingWarrior Avatar answered Nov 25 '25 09:11

StriplingWarrior



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!