2

i am newbie in mvc area. so i am learning still and trying to learn lots of advance area in MVC. so i was reading a post about custom controller factory ASP.Net MVC.

a guy explain so less so 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?

he 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

Luke Girvin
  • 12,913
  • 8
  • 60
  • 81
Thomas
  • 32,301
  • 119
  • 343
  • 612
  • 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,044
  • 18
  • 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
  • 17,769
  • 16
  • 62
  • 107