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

Leave a Comment