I’ve been reading Mark Seemann’s book Dependency Injection in .NET and his blog post regarding DI Composition Roots.
And I’m in the process of refactoring my ASP.MVC 3 application Container calls out of my controllers and into a compositional root.
In the past I’d resolve types inside my controller like this.
[HttpGet]
public ActionResult Create()
{
// Don't do this...
var color = MvcApplication.Container.Resolve<IColor>();
return View(color);
}
After reading Mark’s book I realize this is less then ideal so I’ve setup my MVC application to inject a repository into the controller on app start using a class derived from the IControllerFactory as dicussed in Mark’s book in section 7.2.1.
If I’m not supposed to call an IoC container directly from my ASP.MVC 3 Controller using the Service Locator pattern how and where do I instantiate new types? Each controller is different so I want a generic way of resolving new types.
I could instantiate types directly like this but that would kind of defeat the purpose.
[HttpGet]
public ActionResult Create()
{
// Don't do this...
var color = new Color();
return View(color);
}
Should I be injecting a Generic Factory into my Controller along side the Generic Repository and use it to new create types? Is there a better way?
EDIT
I realize this is similar to another SO question but my entities have dependencies that need to be resolved before passing them on to a view.