Spring.NET - 不建议使用 ContextRegistry.GetContext



我正在构建一个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>

我的问题:为什么使用这个是不明智的? 仅仅是因为我们不需要的 2 行样板吗? AFAIK 我仍在声明最终将在配置中创建什么对象,所以看不到它如何使其更紧密地耦合?

注意:如果我能提供帮助,我真的不想走使用 Spring.Web dll 并通过配置完成所有 DI 的路线!

多谢邓肯

这是一个坏主意,因为您没有使用依赖注入。这不是因为 GetContext 方法的任何线程安全注意事项。您正在使用被认为是不良做法的服务定位器模式 - 类不应负责查询 DI 容器以获取依赖项,应注入这些依赖项。

最佳做法是,应考虑编写基于 Spring.NET 的自定义依赖项解析程序。这样,依赖项将自动注入到控制器和其他类中。

最新更新