Are Consumers of ServiceLocator supposed to call ServiceLocator.Current?
I'm trying to refactor my code to use the Common Service Locator. I have a Shared Library that is used by some other components.
What I don't understand is: Are these components supposed to call ServiceLocator.Current and resolve their types? In that case, how can I make sure that ServiceLocator.Current is actually set? Should I create my own "MyServiceLocator" and add a static constructor? (That seems to defeat the purpose of having a standardized Abstraction)
Or should my Shared Library have a class that exposes all resolvable Types as public properties, thus keeping the ServiceLocator entirely internal to the Shared Library? (which would mean having an abstraction on top of an abstraction on top of an abstraction)?
The thing is that the Components are not created through DI and are supp开发者_JAVA技巧osed to call the Container to get whatever they need.
You shouldn't be using a Service Locator at all. Instead, make sure all consumers of dependencies are open for extensibility by allowing you (or a any DI Container) to inject the appropriate dependencies into them. Constructor Injection is often the best option.
Krzysztof Kozmic recently published a good overview of how a DI Container should be used. His examples use Castle Windsor, but you can extrapolate to any DI Container, as well as Common Service Locator. However, if you follow these principles, Common Service Locator becomes redundant.
精彩评论