Maksim Vi.
Maksim Vi.

Reputation: 9225

Load Controllers at runtime from another assembly

In my project in my main web assembly before I register routes in global.asax I load a number of external assemblies. Some of these assemblies have MVC Controllers and views inside of them.

My problem is that these external controllers are not picked up for some reason, I assume that controller registration happens somewhere before my assemblies are loaded, because if I reference my assemblies before application starts(dlls in bin folder) everything works fine.

So I'm wondering if there`s

I had a similar issue with WebAPI controllers before and I was able to fix it by using my custom HttpControllerSelector, but I wasn't able to find anything similar in MVC yet.

Upvotes: 2

Views: 2611

Answers (1)

Maksim Vi.
Maksim Vi.

Reputation: 9225

was able to solve the issue by overriding DefaultControllerFactory's CreateController method:

Application_Start:

IControllerFactory factory = new ControllerFactory();
ControllerBuilder.Current.SetControllerFactory(factory);

ControllerFactory:

public class ControllerFactory : DefaultControllerFactory
{
    public override IController CreateController(RequestContext requestContext, string controllerName)
    {
         IController controller = null;
         Type controllerType;
         if (ControllerTypes.TryGetValue(controllerName.ToLower(), out controllerType))
         {
              controller = (IController) Activator.CreateInstance(controllerType);
         }
         return controller;
    }
    ...
}

ControllerTypes is a dictionary of my MVC Controllers from external assemblies.

Upvotes: 6

Related Questions