Friday 22 August 2014

Create a custom dependency resolver in ASP.NET MVC4 with IDependencyResolver, SOLID programming

In this post, I will talk about the interface IDependencyResolver and how to use it to build a customized IOC container in ASP.NET MVC4.
In the S.O.L.I.D paradigm, the D says :
" If a class needs one or more dependencies, those dependencies should be provided to the class as abstraction".
In C# language, abstraction means interface. The interface contains some methods signatures but never show how implementations of those methods are done.

A dependency resolver is a "solution" to "resolve" the problem :
"Given an abstraction (interface), how to search and return its real implementation, and if some more implementations are available how to filter them to return the right one ?"
 
This mechanism is also known as Inversion Of Control.

There are several way to feed the class with all dependencies. The most common way is using the class constructor like

public class HomeController(Interface1 interface1, Interface2 interface2 .... InterfaceN interfaceN)

The startup project was a basic MVC project template.


Components framed in orange should be manually create, the global.asax.cs should be modified in this lab.

The IUserService looks like :


IProductService :

ProductService :
ComplexUserService :


DemoController :

I have to notice that the implementation below is commonly used. We should avoid to use it because it's against the S.O.L.I.D. As we can see, the class DemoController is highly coupled to ComplexUserService and ProductService. It would be better if DemoController only know the interface from which they inherit. 





Index.cshtml


 
The interface IDependencyResolver is an interface defined in the namespace System.Web.Mvc :


By inheriting this class, we have to implement two methods :

public object GetService(Type serviceType) : is a 1-to-1 relationship between the "serviceType" ( concretely the interface) and the real implementation ( the return concrete object )
public IEnumerable<object> GetServices(Type serviceType) : is a 1-to-N relationship between the interface ( serviceType ) and all class inheriting this interface.

The full code is shown below.


Global.asax.cs

 
The last line sets the DependencySolverController instance as a resolver in the current domain.
When querying the url http://localhost/Demo/Index, the ASP.NET MVC engine knows that a resolver should be used and all controllers instantiation will be forwarded to the resolver. The resolver uses its internal property Mappings to do the Interface-class resolution.

The current implementation of the IDependencyResolver is just a simple working demo. Many frameworks already exist and are commonly used in many projects : Castle Windsor, Unity, StructureMap, NInject, ....



No comments:

Post a Comment