Inside ASP.NET MVC: ControllerBuilder class
Integral part of MvcHanlder is ControllerBuilder. ControllerBuilder is a singleton that is responsible to produce IControllerFactory instance.
ControllerBuilder have 2 constructors, the default one and one with parameter. One of the major changes between MVC2 and MVC3 was the improvements of Dependency Injection. MVC is using Service Locator pattern for resolving dependencies.Default constructor calls constructor with parameter, passing null as argument, saying that SingleServiceResolver object have to be used as default service resolver.
Please note, even if MVC is using Service Locator to locate different entities (like Controllers, Views, Filters) and so on, it does not include any kind on IoC frameworks itself.
Controller factory get/set
MvcHanlder uses GetControllerFactory method to get controller factory.
Method itself is fairly simple, it just ask service resolver to get current instance of controller factory.
Setter method allows you to change default controller factory with custom one. This an extremely useful then you want to change the way of Controller creation. The most useful case is delegate the controller creation to some DI container (Ninject, Unity, StructureMap) to allowing your application to get benefits of using IoC principles.
Basically, IControllerFactory is a strategy of controller creation. Depending of implementation it might use different techniques, later on we will see how DefaultControllerFactory works.
As and additional option, it is possible to supply custom controller factory just from the specific type
Substitute default controller factory
As you see, we have to options of substitution default factory:
- Call SetControllerFactory method and pass custom object into.
- Implementing new IDependencyResolver.
Here is an example of how that could be done (please note, it is just demostartion.. you typically should not use both approaches in the same type).
ControllerBuilder is simple class that delegates responsibility to IResolver which is responsible to resolve IControllerFactory instance. IControllerFactory is a strategy of controllers creation. ControllerBuilder is designed in a way of chaning this strategy easily, either by using custom IControllerFactory or by custom IDependencyResolver.
What is next?
Next we are going to look closer into SingleServiceResolver and see how it actually acts for resolving types.
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)