Reputation: 4740
I'm studying about Dependency Injection, and I need some help to a better understand about Controller Factory.
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?
Upvotes: 3
Views: 682
Reputation: 156728
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>();
Upvotes: 2