Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In asp.net mvc is it possible to make a generic controller?

I'm attempting to create a generic controller, ie:

public class MyController<T> : Controller where T : SomeType { ... } 

However, when I try to use it, I'm running into this error everywhere...

Controller name must end in 'Controller'

So, my question, Is it possible to make a generic controller in asp.net mvc?

Thanks!

like image 888
Aaron Palmer Avatar asked May 11 '09 16:05

Aaron Palmer


People also ask

Can we have multiple controllers in MVC?

Yes, It is possible to share a view across multiple controllers by putting a view into the shared folder. By doing like this, you can automatically make the view available across multiple controllers.


1 Answers

If I understand you properly, what you are trying to do, is route all requests for a given Model through a generic controller of type T.

You would like the T to vary based on the Model requested.

You would like /Product/Index to trigger MyController<Product>.Index()

This can be accomplished by writing your own IControllerFactory and implementing the CreateController method like this:

public IController CreateController(RequestContext requestContext, string controllerName) {     Type controllerType = Type.GetType("MyController")                               .MakeGenericType(Type.GetType(controllerName));     return Activator.CreateInstance(controllerType) as IController; } 
like image 168
Jeff Fritz Avatar answered Oct 08 '22 09:10

Jeff Fritz