One of the really great things about the ASP.Net MVC framework is how extendable it is. One area of extension is in the area of controller creation. The framework allows you to replace the default ControllerFactory with your own factory and because of this we can incorporate Inversion of Control/Dependency Injection (IoC/DI) into our controller.
Setting up our project for this is very simple and requires very little code.
1) Creating our IoCControllerFactory
We need to create a new factory that will replace the default factory used by the MVC framework.
public class IoCControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(Type controllerType)
{
// if you need more robust logic, add it now
return (Controller) ObjectFactory.GetInstance( controllerType );
}
}
2) Overriding the default ControllerFactory
In order to use our custom factory, we need to set it to the default factory via our Global.asax file. This logic should be put into Application_Start() method
ControllerBuilder.Current.SetControllerFactory( new IoCControllerFactory() );
3) Setting up our IoC/DI container
In order to have StructureMap work we need to wire up all of our dependencies. This could be done here inside (directly) our Global.asax file, but I would suggest putting it into its own class that is just called via the Application_Start() method
StructureMapConfiguration.ForRequestedType<ISomeUsefulService>>().
TheDefaultIsConcreteType<SomeUsefulService>();
The ISomeUsefullService and SomeUsefulService classes are your own classes that will be injected into our controller.
4) Modifying our Controllers for IoC/DI
We now need to modify our controllers to accept the various dependences that will be injected.
public HomeController( ISomeUsefulService someUsefulService)
{
SomeUsefulService = someUsefulService;
}
There you go, it is pretty easy and simply to setup an MVC web project to use IoC/DI in its controllers.
Till next time,
[----- Remember to check out DimeCasts.Net -----]