Injection with Factory Controller

I am learning about Dependency Injection and I need help to understand Factory Controller better.

enter image description here

I need to enter SqlReceitaRepository

through 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 inline, SqlReceitaRepository

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

More details . I am using NHibernate instead of Entity Framework.

Optionally, the classes that will be created to do this will belong to that layer?

I read several articles and I saw that I need to add a new line to my Global.asax

Global.asax

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

      

I am guessing I ReceitaControllerFactory

should contain an implementation IControllerFactory

.

But looking at IControllerFactory

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

      

We can see the CreateController method, but how can I inject an instance SqlReceitaRepository

into a HomeController instance?

+3


source to share


1 answer


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 type of controller as written. More importantly, it is not very convenient. So the correct answer is to get a popular DI framework like Ninject and get the plugins you need for your frameworks (like Ninject MVC), then define your bindings and let the framework take care of figuring out the dependencies:

Bind<IReceitaRepository>().To<SqlReceitaRepository>();

      

+2


source







All Articles