views:

15

answers:

1

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

+1  A: 

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.

Darin Dimitrov
Thanks, I'll have a quick play around with this. I've scarily never had to use reflection as of yet, so this'll be a learning experience for me.
Kezzer
The solution works, however some additional setup must be done by MonoRail as the controllers get null reference exceptions when calling any function on them because the controller context hasn't been instantiated. Will have to work on this...
Kezzer
And your comment is valid by the way, I shouldn't be doing this, but as I say, we're experimenting on some things at the moment. Cheers!
Kezzer