views:

788

answers:

5

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!

+1  A: 

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.

Martin Peck
A: 

If i was you, i'd get the MVC source and create a test MVC project with the source code so you can examine where the exception is generated and see what you can do about your generic idea and the enforced "*controller" naming convention.

cottsak
+1  A: 

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>
{ 
 ...
}
IainMH
I don't want separate Controllers for each type... I want one generic controller to handle many types.
Aaron Palmer
+8  A: 

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;
 }
Jeff Fritz
This is interesting, I'm looking into it. Thanks.
Aaron Palmer
np... Don't forget, the "Controller" naming convention is a DEFAULT STANDARD.. If you want to instantiate in some other way, do it! Write an IControllerFactory that enforces YOUR standard, not MSFT's
Jeff Fritz
A: 

I am getting Object reference not set to an instance of an object. Its not getting type of controller

sushant tawade