I have an ASP.NET MVC 4.0 project with MVC controllers already present, however I'd like to use the class ApiController for some new functionalities.
The existing controller factory returns an IController object which ApiController doesn't inherit from. What would be the best way to make another controller factory for ApiController derived controllers, and make both factories co-exist?
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; } } 1 Answers
Answers 1
You are talking about different type of controllers here, one comes from IController and other is IHttpController. keep your existing factory for MVC controllers and also add
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(); } } you will have to play around with this idea to get what you want. this should take care of your problem. But i still dont understand why you would be doing that as this will cause problems with dependency injection. i will take that you have your reasons.
0 comments:
Post a Comment