通用服务定位器库

工程 | Mark Pollack | 2008年10月3日 | ...

本周在 CodePlex 上发布了 CommonServiceLocator 项目,其总体思路是提供一个与 IoC 容器无关的 API,用于使用服务定位来解析依赖项。来自 SpringSource 的 Erich Eichinger 贡献了 Spring.NET 实现,感谢 Erich!

以下是 API,以便您了解基本概念 public interface IServiceLocator : System.IServiceProvider {

object GetInstance(Type serviceType); object GetInstance(Type serviceType, string key); IEnumerable

GetAllInstances(Type serviceType); TService GetInstance(); TService GetInstance(string key); IEnumerable GetAllInstances(); }

One of the fears I had in participating in this project was that it would promote the approach of Service Location/Dependency Pull over Dependency Injection. I’m glad to see blogs entries like Ayende’s and (more forcefully) Daniel Cuzzulino’s that put this library in the proper perspective.

The intention of this library is primarily for low-level integration between application frameworks. It has a role in business code only as a last resort when you need to ask a container to provide you with a new object instance at runtime that takes advantage of additional container services such as configuration via dependency injection or applying AOP advice. WebForms, WCF Services, and ‘traditional’ server-side objects created at application startup (DAOs, etc) can all be configured non-invasively using dependency injection.

If you find yourself frequently using the service locator approach in your application you should consider refactoring the code to use dependency injection. Not only will you remove an extraneous dependency, always a good thing, but you will get the additional benefit of making your class easier to unit test in isolation of the container as its dependencies will be exposed via standard properties and constructors.

One alternative approach, used in Spring Java but not yet implemented in Spring.NET is to provide a ServiceLocatorFactoryObject, described by my colleague Alef Arendsen here. This allows you to write your own simple service locator interface, for example.

public interface ProcessCreator { Process CreateProcess(string processId); }

The container would provide the implementation dynamically at runtime. You can then use dependency injection to configure your class with a reference to ProcessCreator. The only service locator 'API' provided with ServiceLocatorFactoryObject are of methods with the signatures IMyService GetService() or IMyService GetService(string id) but others could be envisioned.

Get the Spring newsletter

Stay connected with the Spring newsletter

Subscribe

Get ahead

VMware offers training and certification to turbo-charge your progress.

Learn more

Get support

Tanzu Spring offers support and binaries for OpenJDK™, Spring, and Apache Tomcat® in one simple subscription.

Learn more

Upcoming events

Check out all the upcoming events in the Spring community.

View all