IServiceLocator in project Silk

Jul 15, 2013 at 5:15 PM
In project Silk they use IServiceLocator to get an instance of "Handler" classes, what is the benefit of using this?

I mean in the controllers it looks like this:


If they are to hard code the class name they could have gotten an instace of the class the normal way.

Is it just to save one line of code or is there another benefit?
Jul 16, 2013 at 5:34 PM

I believe that the main objective of the Using method is to simplify the creation of the handlers. Let's take for example the ReminderController and the AddReminderToVehicle handler. If you want to create an instance of the handler you will find that its constructor needs two parameters, which means that the ReminderController will need to know those parameters in order to create the handler. What is more, the controller requires several other handlers as well, so it will need to know the parameters to construct all of the handlers it uses.

In order to avoid this, the controllers delegate the creation of the handlers to the ServiceLocator. Finally, by encapsulating the logic to retrieve the handler from the ServiceLocator in the Using method, the syntax of the controller becomes simpler and easier to read.


Damian Cherubini
Jul 20, 2013 at 12:42 PM
Thanks for a good answer.

They could have done this by using only the unity container.

Msdn says:

"In the following situations, it may be appropriate for you to use the IServiceLocator:
•You are an independent software vendor (ISV) designing a third-party service that needs to support multiple containers.
•You are designing a service to be used in an organization where they use multiple containers."

Project Silk is not using multiple containers so maybe its a unnecessary layer of abstraction.