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

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


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;}


Yes you can, it's fine and I've used them lots myself.

What you need to ensure is that when you inherit from MyController you still end the type name with controller:

public class FooController :  MyController<Foo>{  ...}


The default controller factory uses "convention" around controller names when it's trying to find a controller to dispatch the request to. You could override this lookup functionality if you wanted, which could then allow your generic controller to work.

This MSDN article...

http://msdn.microsoft.com/en-us/magazine/dd695917.aspx

... has a good writeup of what's going on.