2012-09-17 130 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