繁体   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