2

I was reading a post about custom controller factory ASP.NET MVC.

Someone explained but I just do not understand how to implement. Here is the post URL In asp.net mvc is it possible to make a generic controller?

They said

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

Need a bit more sample code. Just do not understand where to define CreateController function. Do I need to write this function in base controller?

When request comes like /Product/Index or /Customer/Index then how index method can be invoke in base controller?

So looking for guidance for a newbie like me in MVC advance area. thanks

Dale K
  • 25,246
  • 15
  • 42
  • 71
Thomas
  • 33,544
  • 126
  • 357
  • 626
  • In the answer, it derives from DefaultControllerFactory. For this question, you got to implement IControllerFactory. Deriving from DefaultControllerFactory won't help. – vijayst Nov 18 '13 at 08:53
  • DefaultControllerFactory will also work. The code shown did not have an override, So assumed it requires IControllerFactory. Both methods will work. – vijayst Nov 18 '13 at 09:04

2 Answers2

9

You'll need to implement IControllerFactory (or inherit from DefaultControllerFactory which contains some extra functionality). After that, set your controller factory in Application_Start by using SetControllerFactory method:

ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory());

Hope this clarifies things a bit for you.

volpav
  • 5,090
  • 19
  • 27
  • can u redirect me to any article for IControllerFactory interface. thanks – Thomas Nov 18 '13 at 10:22
  • @Thomas IoC is one of the best examples of using custom controller factories. This article may help you: http://www.mikesdotnetting.com/Article/117/Dependency-Injection-and-Inversion-of-Control-with-ASP.NET-MVC – volpav Nov 18 '13 at 10:49
2
  1. You need to create a class that implements the IControllerFactory interface.
  2. You can ignore the ReleaseController method.
  3. You can return SessionStateBehavior.Default for the GetControllerSessionBehavior method.
  4. In Application_Start, set the Custom ControllerFactory as follows:

    ControllerBuilder.Current.SetControllerFactory(typeof(CCustomControllerFactory));

vijayst
  • 20,359
  • 18
  • 69
  • 113