IServiceLocator in Controller Constructor

Jul 17, 2012 at 4:46 PM

Hi All, 

This code taken from Global.asax file from MilageStats(Project Silk)

  private static void InitializeDependencyInjectionContainer()
  {
     container = new UnityContainerFactory().CreateConfiguredContainer();           
     var serviceLocator = new UnityServiceLocator(container);
     ServiceLocator.SetLocatorProvider(() => serviceLocator);
     DependencyResolver.SetResolver(new UnityDependencyResolver(container));
  }

My Question here is why this ServiceLocator need to be set in Application start event, and required to pass as Parameter(IServiceLocator) in each controller constructor, even though it is possible to implement dependency injection without it by just setting up dependency resolver.

if you can explane and suggest me some link for further reading that will be great.

Thank you

VG

Developer
Jul 17, 2012 at 8:19 PM

Hi,

Based on my understanding, the ServiceLocator is set in the Application_Start with the SetLocatorProvider method in order to register the UnityServiceLocator as the default provider. In order to allow using the ServiceLocator to resolve types from the Unity container.

Regarding the use of the ServiceLocator in the controllers' constructor, you may find that the ServiceLocator is consumed in different controllers by the base AuthorizedController class, where it is used to achieve the generic method Using<T> which is a helper method used to delegate logic to the classes in the services layer.

I believe this is mainly to factor complex methods in controllers' actions into helper methods, in order to prevent having complex conditional logic in these controllers and thus making them easy to unit test.

For more information about this subject, I believe you could check the following section of the Silk documentation:

Additionally, if your are interested in further reading on dependency injection and Unity, the Silk guidance recommends the following resources:

I hope you find this handy,

Agustin Adami
http://blogs.southworks.net/aadami