0

I've just created an MVC project using the .NET 4.5 framework with controllers in a separate class library.

I had previously thought that if the controllers are in separate class library you need to create a custom controller factory as discussed in this SO post. However, my controllers are being instantiated and are working fine without having to do this.

How does the framework (the newer ones at least) know to use the controllers in the separate class libary without being told to do so? All I needed to do was add a reference to the controllers project.

Community
  • 1
  • 1
Mark Erasmus
  • 2,305
  • 6
  • 25
  • 37
  • 4
    They all inherit from the same class which is known to the MVC framework. All they have to do is to find all types that extend that class. – Marcel N. Aug 07 '14 at 17:22
  • Just to add a little to @MarcelN.'s comment, the routing framework uses reflection to load in controller-type classes (it's actually anything that implements `IController`). What assembly it comes from is irrelevant. It then looks for matches on any of these "controllers" to the route that was hit. – Chris Pratt Aug 07 '14 at 17:34
  • So having to create a custom controller factory was never necessary, or has this controller 'auto-detection' been added to newer releases of MVC? – Mark Erasmus Aug 07 '14 at 17:41
  • I also thought default ControllerFactory only knows how to instantiate parameterless controller constructors, but I'm using DI using constructor injection and it's all working fine. – Mark Erasmus Aug 07 '14 at 17:43
  • A customer controller factory was never necessary for this aspect of the framework. It's necessary for other scenarios such as DI. And, if you're using a DI container with your controllers you've got a custom factory, you just may not be aware of it. – Chris Pratt Aug 07 '14 at 18:38
  • @ChrisPratt - not true, MVC has, since version 3 had DI support built in with IDependencyResolver that DI frameworks can hook into so no custom factory is required. – Erik Funkenbusch Aug 08 '14 at 01:47
  • @MarkErasmus - no, as long as the assembly is referenced by your primary assembly, then MVC can find the controller. MVC can also create use constructors with a single constructor that has parameters if something has hooked into the IDependencyResolver hook to do DI (such as NinjectDependencyResolver, WindsorDependencyResolver, UnityDependencyResolver, etc..) You can still do the custom factory route if you wish, but most frameworks will now auto-install the resolver if you use the nuget package to install it. – Erik Funkenbusch Aug 08 '14 at 01:51

0 Answers0