本文內容
- 場景
- 目標
- 解決方案
- 實現細節
- 思考
- 相關模式
- 更多信息
- 參考資料
Common Service Locator 代碼很簡單,它一般不會單獨使用,而是作為一個單件模式,與像 .net Unity 這樣的依賴注入框架一起使用。Common Service Locator 是 Unity 的一部分。
下載 CommonServiceLocator
下載 CommonServiceLocator Demo
場景
假設你有一個類,該類依賴幾個服務 Service(這些服務也可以看做是幾個類),這些服務是在編譯階段指定具體類型的。在接下來的例子中,ClassA 在編譯階段依賴 ServiceA 和 ServiceB。如下圖所示。
這樣做有如下缺點:
- 若替換或更新所依賴的服務(或類),顯然,必須修改源代碼,并且重新編譯解決方案;
- 這些所依賴的具體實現(依賴的服務的具體實現)必須在編譯時可用;
- 你的類很難單獨測試,因為它們直接引用了那些依賴。這意味著這些依賴不能用 stubs 或 mock 對象替換;
- 你的類包含創建、查找和管理這些依賴的重復代碼。
下面說明如何解決這個問題。
目標
使用服務器定位模式可以完成下面的任何一個目標:
- 你想從那些依賴解耦你的類,這樣那些依賴就可以被替換或更新,而不需要或很少修改你的類;
- 你想寫邏輯代碼,而邏輯代碼取決于那些依賴的類,但那些依賴類的具體實現在編譯階段是不知道的;
- 你想在不使用那些依賴的情況下單獨測試你的類;
- 你不想在你的類中寫查找和管理那些依賴類的代碼;
- 你想把你的應用程序劃分成松散的耦合模塊,這樣就可以單獨開發、測試、版本控制和部署。
解決方案
創建一個包含那些服務的引用和封裝了定位他們的邏輯的服務定位器。在你的類中,使用服務定位器來獲得服務的實例。下圖說明了類何使用服務器定位器。
服務器定位器模式不會描述如何實例化服務,它描述一個注冊服務和定位服務的方法。通常情況下,服務定位器模式結合工廠模式(Factory pattern)和/或依賴注入模式(Dependency Injection pattern)。這種組合使得服務定位器創建服務的實例。
注意:
服務定位器可以定位一個服務,而無需知道它的具體類型。例如,它可能使用一個字符串密鑰(string key)或服務接口類型(service interface type)。這樣,你就可以替換依賴的具體實現,而無需修改類。
現實細節
SharePoint Guidance Library 提供了一個服務定位器的實現。SharePointServiceLocator 類提供了訪問單件 IServiceLocator 實例并管理該實例,該類一個接口的默認實現——ActivatingServiceLocator,這個類可以創建和定位服務。
The Partner Portal application 展示了如何使用服務定位器注冊和定位服務,如信息庫(repositories),記錄服務(logging services)和配置管理服務(configuration management services)。更多信息,參看 The SharePoint Service Locator。
思考
在使用服務定位器模式前,考慮下面幾點:
- There are more solution elements to manage.
- You must write additional code that adds service references to the service locator before your objects can use it.
- Your classes have a dependency on the service locator.
- The source code is more complex and difficult to understand.
- You can use configuration data to define run-time relationships.
- You must PRovide implementations of the services. Because the Service Locator pattern decouples service consumers from service providers, it might be necessary to provide additional logic. This logic ensures that the service providers are installed and registered before service consumers try to locate them.
相關模式
下面模式與服務定位器模式有關:
依賴注入(Dependency Injection)。這個模式跟服務定位器模式解決的同一個問題,只是使用了不同的方法。
控制反轉(Inversion of Control)。服務定位器是控制反轉的一個特例。它反轉了一個應用程序的傳統控制流。它是一個被調用的對象,而不是控制處理的調用者。
更多信息
參考:
- Inversion of Control and the Dependency Injection pattern on Martin Fowler's Web site
- Service Locator on MSDN
關于服務定位器,更多資料,參看 The SharePoint Service Locator。
參考資料
- Microsoft Developer Network - The Service Locator Pattern
- The SharePoint Service Locator
- 控制反轉和依賴注入模式 by Martin Fowler
- Service Locator
- Common Service Locator library
- Service Locator is an Anti-Pattern by Mark Seemann
下載 CommonServiceLocator
下載 CommonServiceLocator Demo