Wednesday 2 February 2011

How-to: StructureMap with ASP.NET MVC 3

StructureMap is one of the oldest tools known as "Inversion of Control Container" (IoC Container for short) for .NET developers and it offers the most flexible and easiest configuration. The main idea of the IoC Container is to prevent "Tight Coupling" between classes by using "Dependency Injection" (DI). There are many articles about IoC Containers, DI and why to use them so I just will concentrate on how to configure StructureMap for your ASP.NET MVC3 project.

Assuming you already have ASP.NET MVC3 framework installed, start VS 2010 and create new project "ASP.NET MVC 3 Web Application". I do recommend to select Razor View Engine as compared to ASPX it provides much cleaner interface and it's really easy to use, in fact once you have tried it you'll never go back to ASPX.

The easiest way to add StructureMap reference to you project is to use "Add Library Package Reference..." from  context menu on project "References":


















On the following window select "Online" packages, type "structuremap" into search box and after that locate "structuremap" package in result section, select it and click "Install". TADA! The package will be downloaded into "{YourSolutionFolder}\packages" folder and reference to "StructureMap.dll" is added to project. Neat.










To apply Dependency Injection into controller's constructor let's add some code.

1.  Create custom ControllerFactory class: