Friday, July 29, 2011

Zen and the Art of Dependency Injection in MVC

Let me start off on a modest note: I am not an expert on dependency injection.
I am, however, certain of the value that it provides.

TDD

After having engaged in the same conversation time and time again, I have become convinced that there is indeed "one simple way to get any developer to write better code." That is because every developer, Junior or Senior, C# or Java, can always engage in more Test Driven Development with Dependency Injection. These are best practices that we can all agree on and that will always result in better and more maintainable code.

If you are already doing TDD with Dependency Injection, keep it up and help spread the word! If you are not, it's time to start. On the plus side, thanks to tools like NuGet, it has never been easier to get started with all of these new fun techniques. :)

Dependency Injection

Dependency Injection is a universally accepted best practice for a number or reasons, not the least of which is how easy it makes unit testing. You should be able to test one section of code without having to rely on the other 99% of your application. By injecting dependencies you are able to control what code is being tested with pin point precision.

A little ant can't move a lake, nor should it want to. However with a little help from a good surface tension framework, it can easily move a drop of water.

MVC

The MVC architecture provides you with a consistent entry point into your code: controller actions. All requests come in and get processed the same way, always passing through a consistent set of action filters and model binders. Right out of the box the MVC model binders are already injecting models straight into your controllers, so why not take it one more step forward and inject your services too?

My controller actions almost always need two things: 1) a model and 2) a service to process that model. So let the MVC model binder manage the RequestContext and inject your model, and let a DI framework manage the logic by injecting your service.

NuGet

To get started (after having installed NuGet) you need look no farther than Tools -> Library Package Manager -> Manage NuGet Packages. If you search for Ninject, a MVC3 specific package will come up that can install itself straight into your MVC3 project and get you going in mere seconds.

Ninject is just one choice of Dependency Injection framework, and it has great documentation. If you would prefer something else then just pick your flavor of choice and keep on moving.

Example

Create your controllers, models and services like normal, and update your controller to take in a service dependency through it's constructor.

public class CalculatorController : Controller
{
     public ICalculatorService CalculatorService {get; private set;}
     public CalculatorController(ICalculatorService calculatorService)
     {
         CalculatorService = calculatorService;
     }

Then all that you have left to do is create a model that binds the service type to it's interface...

public class MvcExampleModule : NinjectModule
{
     public override void Load()
     {
         Bind<ICalculatorService>().To<CalculatorService>();
     }
}

...and load that in the static RegisterServices method.

public static class NinjectMVC3
{
     private static void RegisterServices(IKernel kernel)
     {
          var module = new MvcExampleModule();
          kernel.Load(module);
     }

That's it. That is all that you have to do to start using Dependency Injection.
Want proof? Download the sample application.

Enjoy!
Tom

No comments:

Post a Comment

Real Time Web Analytics