One thing, that I have seen done wrong in so many ways, is DI in relation to ASP.NET MVC. Just to get things straight for everyone – including those, who have been living under a rock for the last 30 years – here’s a glossary:
- Dependency injection (DI) – is exactly what it says, i.e. dependencies are injected. So your business methods don’t just instantiate order processors, they have them injected for them to use.
- Inversion of control (IoC) – is when program flow is no longer just sequential. In many cases just a fancy term for a callback. In this case, it signifies that your classes may call stuff on instances on other classes, that are handed to them – which happens by DI.
- IoC container – is a thing, that facilitates the above and removes the pain.
Quick, off the top of my head implementation of an ASP.NET MVC action method
1 2 3 4 5 6 |
public ActionResult Index() { var productService = new ProductService(); var productsOnSale = productService.GetProductsOnSale(); return View("Index", new ProductListViewModel(productsOnSale); } |
Now what happens when we want to test this? Well, we definitely need the database to be there, otherwise we will probably get some nasty SqlException stuff happening. There may be other stuff going on, we don’t know. Or even if we know now, we will not have a clue in a few months! – because what if some class, on which our ProductService depends, changes? Or changes its dependencies? The product service is tightly coupled to everything that is architecturally beneath it. We need inversion of control!
Naïve IoC/DI example
1 2 3 4 5 6 7 8 9 |
public ActionResult Index() { var sessionProvider = new NHibernateSessionProvider(); var productRepository = new ProductRepository(sessionProvider); var productIsOnSaleSpecification = new ProductIsOnSaleAccordingToSomeFunkyRulesSpecification(); var productService = new ProductService(productRepository, productIsOnSaleSpecification); var productsOnSale = productService.GetProductsOnSale(); return View("Index", new ProductListViewModel(productsOnSale); } |
Now, we have DI-enabled our service layer. It can be seen that the repository gets its NHibernate ISession from a session provider, that can probably be configured with a connection string somewhere. And we have a complex business rule inside a specification, and a service to use the repository and the specification together. This is much better, because all dependencies are explicit and injected from the outside. But this code is still not perfect – there’s way too much going on, the classes are all concrete, and there is no way to test the action method without instantiating all this stuff. And what happens when the product service is used in 100’s of places in the system, and suddenly it needs another specification in its constructor to decide whether the current user can be given a rebate? Damn! Back to work… let’s try again:
Service locator IoC/DI example
1 2 3 4 5 6 |
public ActionResult Index() { var productService = MyContainer.Resolve<IProductService>(); var productsOnSale = productService.GetProductsOnSale(); return View("Index", new ProductListViewModel(productsOnSale); } |
Now it’s much clearer again. But what is MyContainer? Well, it’s actually pretty simple: it’s a generic factory! And this time we are using the factory to supply a dependency when we need it and let the factory decide where to get it. Then it may deliver a new instance, an instance from a pool, an instance tied to the current HttpRequest or a singleton or whatever it feels like. This is the service locator pattern, and it’s better than the second example, but still – your code will be cluttered with calls to your container, so unit testing will not be as easy because your need to have a container in place or mock it.
This brings me to how to do it with ASP.NET MVC – the important thing is that we have one single call to container.Resolve<...>. We do it by taking control over how controllers are created, because the controller creation is the single entry point into as ASP.NET MVC application. Here goes:
ASP.NET MVC with IoC/DI
global.asax
1 2 3 4 5 6 7 |
void Application_Start() { // RegisterRoutes(...) // installs our controller factory at application startup ControllerBuilder.SetDefaultControllerFactory(typeof(MyControllerFactory)); } |
MyControllerFactory.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class MyControllerFactory : IControllerFactory { static IContainer myContainer = GetContainerInstanceFromSomewhere(); public IController CreateController(RequestContext context, string name) { // looks up controller registered under lowercase key - e.g. "home" for HomeController var key = name.ToLowerInvariant(); return myContainer.Resolve(key); } public void ReleaseController(IController controller) { // releases any IDisposables inside this controller MyContainer.Release(controller); } } |
And now – the best thing about DI: The class is pure! Look!
ProductsOnSaleController.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class ProductsOnSaleController : Controller { public ProductsOnSale(IProductService productService) { this.productService = productService; } public ActionResult Index() { var productsOnSale = productService.GetProductsOnSale(); return View("Index", new ProductListViewModel(productsOnSale); } } |
It is plain and simple, depending on a product service only, which gets automatically injected by the container. Easy to test, easy to extend. And we are probably going to write 100’s and 1000’s of action methods, so we are going to save a lot of work and grief on that account – thanks to DI and IoC.
I think this is THE way to do dependency injection in ASP.NET MVC controllers. I will show in another post how you can configure Castle Windsor with ASP.NET MVC to support multiple configurations (e.g. IEmailService is FakeLoggingEmailService on the developers’ machines and RealLiveSmtpEmailService in a production environment.