tags:

views:

69

answers:

2

I have a list of controller names and their actions names. What I need to do is to read values from custom attributes on those actions. The problem is that it seems there is no easy way to get controller types (Having that the rest is easy.) ASP.NET MVC framework has this functionality in DefaultControllerFactory, but it's not accessible outside of framework itself. It doesn't look like a good idea to reinvent the wheel and implement it myself, especially because MVC framework has cache for controller types, which I would need to duplicate. Is there any better solution?


Upd. http://stackoverflow.com/questions/790464 describes a similar, but different problem. I don't need to determine what controllers/actions are available to be executed, I need to get type of a single controller.

A: 

I'm not really clear on where you need to do this. If you need to do this inside your MVC app then you could implement your own controller factory and put your code in there, storing the results with a cache keyed on controller type - e.g.:

public class CustomControllerFactory : DefaultControllerFactory
{
  protected override IController GetControllerInstance(Type controllerType)
  {
    // do something with controller attributes on controllerType here the
    // first time a controller is seen and store the results in a
    // static cache keyed on the controller type

    return base.GetControllerInstance(controllerType);
  }
}

and then register that ControllerFactory on application startup (e.g. in global.asax):

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

Alternatively, you could simply use reflection to look for all classes in your assembly that end with "Controller" and run your code on there - again, I'm unclear on where you need this to happen.

Steve Willcock
A: 

Since you already have a list of typenames, using reflection to rip through the assembly, retrieve the type, and iterate the actions, checking for the existence of the interesting attribute, is probably the most direct method. I haven't done enough crawling around in ASP.Net MVC to know if there might be a way to extract the type information from the controller cache in MVC...

Alternatively, if you can ask the cache for an object of each controller type (and ASP.Net MVC controllers, or more specifically your controllers, are cheap enough to construct, or are constructed and cached, an unknown for me), retrieving each of the controllers in the system and retrieving their type might be more direct.

Tetsujin no Oni