这对我来说适用于 MVC3 RC。注意 IControllerFactory 现在在 MVC3 RC 中有 GetControllerSessionBehavior。
UnityMvcControllerFactory.cs:
using System;
using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.Practices.Unity;
using System.Web.SessionState;
public class UnityMvcControllerFactory : IControllerFactory
{
private IUnityContainer _container;
private IControllerFactory _innerFactory;
public UnityMvcControllerFactory(IUnityContainer container)
: this(container, new DefaultControllerFactory())
{
}
protected UnityMvcControllerFactory(IUnityContainer container,
IControllerFactory innerFactory)
{
_container = container;
_innerFactory = innerFactory;
}
public IController CreateController(RequestContext requestContext, string controllerName)
{
try
{
return _container.Resolve<IController>(controllerName.ToLowerInvariant());
}
catch (Exception)
{
return _innerFactory.CreateController(requestContext, controllerName);
}
}
public void ReleaseController(IController controller)
{
_container.Teardown(controller);
}
public SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName)
{
return SessionStateBehavior.Default;
}
}
全球.asax.cs:
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
// Register Types and Set Controller Factory
ConfigureUnityContainer();
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
private static void ConfigureUnityContainer()
{
IUnityContainer container = new UnityContainer();
// Set Controller Factory as UnityMvcControllerFactory
ControllerBuilder.Current.SetControllerFactory(
new UnityMvcControllerFactory(container)
);
}
}