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

2
  • In the answer, it derives from DefaultControllerFactory. For this question, you got to implement IControllerFactory. Deriving from DefaultControllerFactory won't help. Commented Nov 18, 2013 at 8:53
  • DefaultControllerFactory will also work. The code shown did not have an override, So assumed it requires IControllerFactory. Both methods will work. Commented Nov 18, 2013 at 9:04

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

can u redirect me to any article for IControllerFactory interface. thanks
@Thomas IoC is one of the best examples of using custom controller factories. This article may help you: mikesdotnetting.com/Article/117/…
1
  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));

1 Comment

can u redirect me to any article for IControllerFactory interface. thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.