http://www.cnblogs.com/hwade/archive/2011/01/30/CommonServiceLocator.htmlhtml
起源于同事发给个人连接 http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/单元测试
结合总结工做中使用ServiceLoactor模式遇到的问题。测试
var instance1 = ServiceLocator.Current.GetInstance
var instance2 = ServiceLocator.Current.GetInstance
以上客户端程序中出现这样的代码。是否 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