Update! Download sample project MvcWithUnity.VS2010.zip
After my previous post, new versions of both ASP.NET MVC and Unity has been released and some confusion about their compatibility has shown up on the Internet. The first hit on Google on the topic is this which is completely wrong and uninformed. BillKrat writes:
"MVC2 will pull the rug out from under these blogs because the IControllerFactory interface for CreateController no longer provides a "type" - it provides a "string" which will simply hold the controllerName; not as easy to work with."
In fact, this is not the case at all. The following snippet is fresh out of the code repository from the MVC 1.0 relase:
1: public interface IControllerFactory
2: {
3: IController CreateController(RequestContext requestContext,
4: string controllerName);
5: void ReleaseController(IController controller);
6: }
thus, the interface has not changed at all, and all samples on integrating ASP.NET MVC with Unity still apply!
What BillKrat has done is to mistake the interface for the base implementation in System.Web.Mvc.DefaultControllerFactory. If we subclass DefaultControllerFactorty all we need to do is this (as I’ve explained previously):
1: public class UnityControllerFactory : DefaultControllerFactory
2: {
3: private readonly IUnityContainer container;
4: public UnityControllerFactory(IUnityContainer container)
5: {
6: this.container = container;
7: }
8: protected override IController GetControllerInstance(
9: RequestContext requestContext, Type controllerType)
10: {
11: return container.Resolve(controllerType) as IController;
12: }
13: }
thus, here we get our type which plays very nicely with Unity’s Resolve method.