Question

Loosely related to this post, I need to get a list of all controllers in the controllers folder. We're just experimenting with some stuff at the moment. I've searched through API's etc. without any luck. I can get the current controller just fine, but not the others unfortunately.

I've had to statically create a list of instantiated controllers that I want, like so:

public static IList<AbstractHtmlPageController> _controllers = new List<AbstractHtmlPageController>
{
    new HomeController(),
    new UserController()
};

This obviously isn't a desirable solution.

Cheers

Was it helpful?

Solution

You could try using reflection (haven't tested):

public static IList<AbstractHtmlPageController> GetControllers()
{
    Assembly
        .GetExecutingAssembly()
        .GetTypes()
        .Where(t => 
            t != typeof(AbstractHtmlPageController) && 
            typeof(AbstractHtmlPageController).IsAssignableFrom(t)
        )
        .Select(t => (AbstractHtmlPageController)Activator.CreateInstance(t))
        .ToList();
}

The usefulness of such a method is highly doubtful. Instantiating controllers like this for the lifetime of the application can be dangerous. Controllers shouldn't be shared. Leave the instantiation of your controllers to the dependency injection framework you are using. Their lifetime should be very short, preferably limited to the current user request.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top