Here’s an easier way to do dependency injection and build controllers without parameterless constructors in ASP.NET MVC. If you want cleaner code and easier unit tests for your controllers and BLLs, follow the instructions below to use top-down dependency injection using Structure Map.

1. Replace the default System.Web.Mvc.ControllerBuilder with a StructureMap controller factory: First, create a new class called StructureMapControllerFactory in the presentation layer.

using System;
using System.Diagnostics;
using System.Web.Mvc;
using StructureMap;
namespace MyWebApp
{
/// <summary>
/// Used in Global.asax's Application_Start method to replace the default System.Web.Mvc.ControllerBuilder with this StructureMap controller factory.
/// </summary>
public class StructureMapControllerFactory : DefaultControllerFactory
{
/// <summary>
/// Use StructureMap to construct the controller and all its dependencies.
/// </summary>
/// <param name="controllerType">Type of the controller.</param>
/// <returns>A reference to the controller.</returns>
protected override IController GetControllerInstance(Type controllerType)
{
if (controllerType == null)
return null;
return ObjectFactory.GetInstance(controllerType) as Controller;
}
}
}

2. Then use the new StructureMapControllerFactory in Global.asax.cs’s Application_Start method. Add this line right below the Bootstrapper.Bootstrap() call:

ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());

3. You don’t need a parameterless constructor for your controllers anymore. Make sure you pass in any dependent blls/etc. in all of your controllers’ constructors (i.e. don’t use ObjectFactory). Like this:

private readonly IMyBLL myBLL;public MyController(IMyBLL myBLL){this.myBLL = myBLL;}

4. Make sure you pass in dependent blls/dals /etc. in all of your BLLs’ constructors (i.e. don’t use ObjectFactory). Like this:

private readonly IMyDAL myDAL;
public MyBLL(IMyDAL myDAL){this.myDAL = myDAL;}

« »