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

相關文章
相關標籤/搜索