我有一个MVC控制器已经存在的ASP.NET MVC 4.0项目,但是我想使用类ApiController
来实现一些新的功能。
现有控制器工厂返回IController
对象ApiController
未继承的对象。为ApiController
派生控制器创建另一个控制器工厂的最佳方法是什么,并使两个工厂共存?
ControllerBuilder.Current.SetControllerFactory((IControllerFactory)new BuilderControllers.BuilderControllerFactory());
public class BuilderControllerFactory :IControllerFactory
{
public IController CreateController(RequestContext requestContext, string controllerName)
{
string controllerType = string.Format("BuilderControllers.{0}Controller", controllerName);
IController controller = null;
try
{
controller = Activator.CreateInstance(Type.GetType(controllerType)) as IController;
}
catch (System.Exception x)
{
//-- handle any failed requests --
}
return controller;
}
}
答案 0 :(得分:0)
你在谈论不同类型的控制器,一个来自IController,另一个来自IHttpController。保留现有的MVC控制器工厂并添加
GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator),new MyControllerActivator());
GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerSelector),new MyControllerSelector());
public class MyControllerActivator : IHttpControllerActivator
{
public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
{
throw new NotImplementedException();
}
}
public class MyControllerSelector : IHttpControllerSelector
{
public HttpControllerDescriptor SelectController(HttpRequestMessage request)
{
return new HttpControllerDescriptor() {ControllerName="SomeController",ControllerType=typeof(MyApiController),Configuration=GlobalConfiguration.Configuration};
}
public IDictionary<string, HttpControllerDescriptor> GetControllerMapping()
{
throw new NotImplementedException();
}
}
你将不得不玩这个想法来获得你想要的东西。 这应该照顾你的问题。但我仍然不明白为什么你会这样做,因为这将导致依赖注入的问题。我会认为你有理由。