Monday, February 22, 2010

Creating an ASP.NET MVC 2 Controller Factory with Ninject

Introduction



Recently I've been getting into Test Driven Development and one useful thing that helps me out with this is making use of the Inversion of control principle. This makes it easy to pass a Mock version of all my services for the purposes of testing.

However this presents a challenge with the standard MVC Controller Factory. It only supports the parameterless contructors. However, one of the great things about ASP.NET MVC (2) is that it allows you to override most aspects of the framework. It doesn't restrict you as much as it's ASP.NET webforms predecessor. So to avoid the so call "Anti Pattern" of having both a Parameterless Constructor for your "Real Services" and an overloaded constructor for your testing/Mock Services, you can follow this guide to create a Controller Factory which uses ninject. Then you'll only have 1 constructor and you'll sleep soundly.

Creating Ninject Controller Factory