MVC 2 Beta DefaultControllerFactory 带区域 [英] MVC 2 Beta DefaultControllerFactory with Areas
问题描述
为什么默认工厂不会返回控制器的全名(带命名空间)?我正在使用服务定位器和 autofac.
Why default factory WON'T return full name of the controllers (with namespaces)? I'm using Service Locator and autofac.
using System.Web.Mvc;
using Microsoft.Practices.ServiceLocation;
namespace Application.Core.MVC
{
public override IController CreateController(System.Web.Routing.RequestContext requestContext, string **controllerName**)
{
return ServiceLocator.Current.GetInstance<IController>(controllerName);
}
}
我有两个家庭控制器(一个在博客区域下)
I had two home controllers (one under area Blog)
controllerName 在上面的代码中只返回Home"而没有完全限定的名称.当我尝试为依赖项注入注册控制器的名称时,这会产生问题.这是我现在根据这种情况注册控制器的方法.即使这样也无一例外地调出页面.但是当我访问 http://localhost/Home 时,两个控制器都会调用.
controllerName return only "Home" without full qualified name for both in above code. This creates a problem when I try to regiser controllers' names for dependency injection. Here is how I register controllers right now according to this situation. Even this brings up the pages without exception. But When I access http://localhost/Home, both controllers invoked regardlessly.
foreach (var tp in currentAssemblyControllersTypes)
builder.Register(tp).FactoryScoped().Named(tp.Name.Replace("Controller", ""));
有人可以帮忙吗?谢谢.
Anyone can help?Thanks.
推荐答案
DefaultControllerFactory.CreateController() 方法负责为给定的请求返回一个控制器.controllerName 参数只是路由的 {controller} 部分.CreateController() 的工作 - 而不是它的调用者 - 根据 URL 中指定的控制器名称找出正确的类型.
The DefaultControllerFactory.CreateController() method is responsible for returning a controller for the given request. The controllerName parameter is just the {controller} part of the route. It's CreateController()'s job - not its caller's - to figure out the proper type given the controller name as specified in the URL.
为了使这更容易,DefaultControllerFactory.CreateController() 委托给另外两个方法:GetControllerType() 和 GetControllerInstance().如果您想使用原始控制器解析逻辑(例如类型查找)但只是更改类型的实例化方式,请保持 CreateController() 和 GetControllerType() 方法不变,只需覆盖 GetControllerInstance().这已经处理了您正在复制的命名空间查找逻辑,并使您的代码更加简单.
To make this easier, DefaultControllerFactory.CreateController() delegates into two other methods: GetControllerType() and GetControllerInstance(). If you want to use the original controller resolution logic (e.g. type lookup) but just change how types are instantiated, leave the CreateController() and GetControllerType() methods as-is, and just override GetControllerInstance(). This already takes care of the namespace lookup logic you're duplicating and will make your code far simpler.
这篇关于MVC 2 Beta DefaultControllerFactory 带区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!