Could a static ServiceLocator be dangerous?

Oct 3, 2008 at 10:25 AM
Hej,

first off, thank you for putting your time into designing this project! Also, let me acknowledge that much more experienced developers than me have spent quite some time on this generic IoC abstraction. That said, everything below this paragraph may be total bullshit because I misunderstood something. :)

Having the possibility to use a generic service locator which is (hopefully) implemented by big IoC containers and friends most certainly is a big advantage. However, I wonder whether having a static ServiceLocator could be dangerous in this case. (No, I do not have an alternate suggestion at this moment.) Let me explain:

Someone who creates a class library could just use ServiceLocator.Current to fetch an instance of an object implementing the desired interface. This could be seen as an advantage, but as far as I understood IoC this would be wrong in so far that the class consuming an interface should not be involved into the object's creation in such a way. Instead, they should just accept an object implementing the interface in a constructor, property, …, right?

Now, CommonServiceLocator should not be blamed for such a possible misuse (?) of the ServiceLocator class, but do you think this could be avoided? Maybe I also misunderstood a part of the IoC concept and this is actually a feature … :)

-hangy
Developer
Oct 4, 2008 at 6:59 PM

While ideally you should inject everything everywhere, there are times when you want to defer construction until later in your application. That's when you'd either use the static ServiceLocator, or have a saved away IServiceLocator you can call back into later. This is equivalent to a container registering itself, and then an object getting the container injected and using it later to resolve stuff.

Is it ideal? Probably not. But it is a real need, especially in the case when you have multiple disjoint libraries, all of which need a container, and you want them to share one across the application. Dangerous? Maybe, but you can't stop stupid things from happening. Think of it as a really sharp kitchen knife. ;-)

Also, the static locator is completely optional. You can write your library so that it recieves the IServiceLocator instance directly instead.

 

Oct 5, 2008 at 9:46 AM
Okay, I got you. Thanks for your reply! :)