簡體   English   中英

Spring.NET - 不建議使用ContextRegistry.GetContext?

[英]Spring.NET - using ContextRegistry.GetContext is not advised?

我正在構建一個MVC 3站點,並希望使用Spring來提供我的Web服務適配器的運行時注入,這樣我就可以在模擬服務調用中存根而不是調用真正的交易。

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

我之前在Spring線程安全方面受到了攻擊,其中單例並非“假”,因此請查看Spring源代碼以仔細檢查以上是否是線程安全的。

來源在評論中有這個:

/// 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,如果我能幫忙的話!

非常感謝鄧肯

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

作為最佳實踐,您應該考慮編寫基於Spring.NET的自定義依賴項解析程序 這種方式依賴關系將自動注入控制器和其他類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM