ServiceLocator是反模式

关于ServiceLocator模式

http://www.cnblogs.com/hwade/archive/2011/01/30/CommonServiceLocator.htmlhtml

为何是Anti-Pattern

起源于同事发给个人连接 http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/单元测试

结合总结工做中使用ServiceLoactor模式遇到的问题。测试

  1. 依赖关系不明确,ServiceLoactor在各个方法中使用,没法直观了解对象之间的引用
  2. 若是对象未正确注册,只有执行到ServiceLoactor.Resolve时才会抛出Exception。使用构造器注入能够更早发现问题。
  3. 维护对象以及生命周期的控制。

var instance1 = ServiceLocator.Current.GetInstance ();
var instance2 = ServiceLocator.Current.GetInstance ();
htm

以上客户端程序中出现这样的代码。是否 instance1 == instance2 ?
光看这段方法这是没法肯定的。 致使误解形成程序预期以外的的运行结果。甚至在其余对象中调用了ServiceLocator.Current.GetInstance ()而且修改了内部状态致使异常结果。 对象

在MVC中也实现了ServiceLocator模式blog

//容器集成MVC
var locator = new NinjectServiceLocator(kernel);
DependencyResolver.SetResolver(locator);生命周期

//使用
var customerService = System.Web.Mvc.DependencyResolver.Current.GetService(typeof (ICustomerService));get

这个对象没法在非MVC中复用运行,在单元测试时,也必须提早初始化DependencyResolver.Currentit

总结

标题党了“Anti-Pattern”,不是说它很差不能用。其实只是须要注意使用的方法。一个好东西不注意使用方式或者滥用就失去了它的意义。io

相关文章
相关标签/搜索