2012-09-17 134 views
0

我正在構建一個MVC 3網站,並且希望使用Spring來提供運行時注入我的Web服務適配器,以便我可以存模擬服務調用而不是調用真正的交易。Spring.NET - 不建議使用ContextRegistry.GetContext?

var ctx = ContextRegistry.GetContext(); 
var serviceAdapter = (IServiceAdapter) ctx[Constants.C_ServiceAdapter]; 
... 
serviceAdapter.doSomething(); 

我一直在春季線程安全的,其中單是不是「假」蜇傷過,所以看了看春源仔細檢查上面的是線程安全的。

源有這評論:

/// A singleton implementation to access one or more application contexts. Application 
/// context instances are cached. 
/// </p> 
/// <p>Note that the use of this class or similar is unnecessary except (sometimes) for 
/// a small amount of glue code. Excessive usage will lead to code that is more tightly 
/// coupled, and harder to modify or test. Consider refactoring your code to use standard 
/// Dependency Injection techniques or implement the interface IApplicationContextAware to 
/// obtain a reference to an application context.</p> 

我的問題:爲什麼採用這種不明智的?僅僅是因爲我們不需要兩條鍋爐板? AFAIK我仍然聲明最終將在配置中創建哪個對象,所以不明白它是如何使它更加緊密耦合?

注意:我真的不想去使用Spring.Web dll並通過配置完成所有DI的配置,如果我能幫上忙的話!

非常感謝 鄧肯

回答

2

它,因爲你不使用依賴注入是一個壞主意。這不是因爲GetContext方法的任何線程安全考慮。您正在使用服務定位器模式,這被認爲是不好的做法 - 類不應該負責查詢DI容器來獲取依賴關係,應該注入這些依賴關係。

作爲一個最佳實踐,您應該考慮編寫基於Spring.NET的自定義dependency resolver。這種方式依賴會自動注入到控制器和其他類中。

+0

謝謝,這很有道理 - 執行「熱插拔」的組件本身需要「熱插拔」!我只使用這3次在我的整個應用程序調用,所以編寫一個依賴解析器似乎有點矯枉過正,但會嘗試和實現它在這裏(時間允許!) – Duncan

+1

+1,但注意春天1.3.1和[更高支持mvc 3.0](http://www.springframework.net/doc-latest/reference/html/web-mvc3.html),包括[IDependencyResolver的實現](https://github.com/SpringSource/)彈簧淨/斑點/主/ SRC /彈簧/ Spring.Web.Mvc3/SpringMvcDependencyResolver.cs) – Marijn