2

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

  • a way to control when mvc controllers are registered, so I can do it after all my assemblies are loaded? OR
  • a way to inject my external controllers?

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.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Maksim Vi.
  • 9,107
  • 12
  • 59
  • 85
  • Create your own controller factory? Use a DI container that can include multiple sources (most have this functionality in their configuration, e.g. `cfg.FromAssembly("My.Other.Asm")` – Brad Christie Jul 17 '13 at 19:03

1 Answers1

6

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.

Maksim Vi.
  • 9,107
  • 12
  • 59
  • 85