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