For past couple of days we were checking out features of the new ASP.NET MVC Preview 3.There are couple of interesting new additions like integration with the new Razor viewengine,improvements in Model Validation,AJAX support and Dependency Injection. In this post we will discuss on, how ASP.NET MVC 3 has streamlined the ability to register/retrieve objects/services in a loosely coupled manner by incorporating support for the Common Service Locator framework.
What is Common Service Locator?Today we have many Inversion of Control/Dependency Injection Containers like NInject,StructureMap,Unity,.. etc in the .NET world.Most of these vary quite widely in terms of configuration and initialization/registration of the instances.But they provide more or less similar interface while resolving the dependencies and returning object instances.Common Service Locator framework extracts these commonalities out and provides an abstraction on top of these IoC/DI containers.This is now part of the Enterprise Library 5.0 and used in the Enterprise Library code to create/retrieve objects.Common Service Locator provides an interface IServiceLocator
It is quite evident from the method signatures that these are only related to retrieval of right object instances with proper resolution of the dependencies based upon different parameters.
Another important class related to the Common Service Locator is the ActivationException which needs to be thrown whenever there is exception in instantiating the objects /resolving the dependencies.
We were planning to use StructureMap as the DI Container and a StructureMap Adapter for Service Locator was available in Codeplex but that seemed far from complete.
So we went ahead to write few lines of code and develop a service locator which will use StructureMap as the DI container as shown below:
This class accepts an instance of the StructureMap.Container in the constructor and uses it to resolve dependencies and instantiate objects.In the implementation of the IServiceLocator methods we have to just map them suitably to StructureMap.Container.GetAllInstances and StructureMap.Container.GetInstance methods (and their overloads).The code which depends on IServiceLocator will perform exception handling based on ActivationException class whereas StructureMap raises StructureMap.StructureMapException in most of the cases.So we need to catch StructureMapException in this class and throw a ActivationException.The complete code is given below:
So we have our Service Locator class ready.In next part of the post we will see how we can plug this into the ASP.NET MVC 3.0 Framework