Reputation: 1233
I have a number of MVC.NET apps in v1, v2 and (soon) v3.
Many of the apps use a repository pattern (subsonic) and each controller injects the repository as below;
public class DefaultController : Controller
{
private readonly iRepository repo;
public DefaultController() : this(new Repository()) { }
public DefaultController(iRepository repository) { repo = repository; }
//
// GET: /Default/
public ActionResult Index()
{
ViewData["HelloWorld"] = repo.GetData("test");
return View();
}
}
Would Ninject (or simlar) allow me make the link only once (in my global asax) and what shoudl this look like?
Are there any additional benefits other than saving time when creating new constructors?
Upvotes: 0
Views: 264
Reputation: 12624
What you are doing here is "poor man's" dependency injection. You are saying that if the caller does not provide an instance, use this one (new Repository). So, what an IoC container like Ninject (Autofac, Windsor, Structuremap, etc...) will give you is a couple of things.
1) If you need to to make sweeping changes and change your default implementation from Repository to MyAwesomeRepository, you would do that in one place instead of in all the different controllers.
2) You would be able to get rid of your default constructor and only have the one that takes an iRepository.
I think it is well worth your time to investigate using an IoC container rather than doing the above.
So, it would look similiar to this:
//global asax
void Application_Load()
{
IKernel kernel = new StandardKernel();
kernel.Bind<iRepository>().To<Repository>();
DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
}
You can follow up here for how to get the dependency resolver working: http://www.shahnawazk.com/2010/12/dependency-injection-in-aspnet-mvc-3.html
Upvotes: 4