ControllerFactory for ApiController in MVC4
本文关键字:MVC4 in ApiController for ControllerFactory | 更新日期: 2023-09-27 18:36:11
我有一个 ASP.NET MVC 4.0项目,其中已经存在MVC控制器,但是我想使用类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;
}
}
您在这里谈论的是不同类型的控制器,一个来自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();
}
}
你将不得不玩弄这个想法才能得到你想要的东西。这应该可以解决您的问题。但我仍然不明白你为什么要这样做,因为这会导致依赖注入问题。我会认为你有你的理由。