Replacing Singletons With ServiceLocators when using Dependency Injection

I wrote a big application using DI. The application is composed by a bootstrapper upon initialization, where most dependencies are injected. All is fine.

However, there are some services* that I can't simply inject everywhere. One good example is the Log service. It's a log, so, every single class in the solution may want to use it for debugging or tracing purposes. Not every class is created upon initialization, some are provided by third party (the application is somewhat a framework). Right now, my solution is to use singletons; I even created some wrapper classes for the singleton, so I can inject it where possible.

I was wondering if a better approach would be to use a ServiceLocator in those places. This would complete remove the hard coupling that a singleton causes. Classes would be coupled to the locator, yes, but I could provide any implementation to them.

*In the DDD terminology.

PS: I'm using .NET here, but I won't tag it so; I believe the question applies to any language that accepts DI.


In Java EE 6/7 enviroment, the best option for cross-cutting aspects is to use interceptors. The cross cutting functionality can be easily factored out into reusable interceptors. I don't know if there is something similar in .NET.

In another way, the design pattern Service Locator has been replaced in some degree by CDI. The pattern isolates to the application code from the details of the service implementation. CDI can provide the same level of isolation from service details, but in more easy way.

Just in case you need to maintain the state of a bean during the lifetime of the application, you should use a @Singleton .

The above applies to Java EE 6/7 environment.


Adding on to Paul Vargas... A concept similar to interceptors is that of aspect-oriented programming (AOP), which is probably what you want to look into.

I'm not sure which DI framework you're using. If you're using Spring .NET, the functionality is definitely available. This is useful, for example, in adding debug- or trace-level logging as you enter and exit each method call.

http://www.springframework.net/doc/reference/html/aop-quickstart.html

链接地址: http://www.djcxy.com/p/77712.html

上一篇: 服务定位器和依赖注入

下一篇: 使用依赖注入时使用ServiceLocator替换单例