简体   繁体   English

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

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

I'm building an MVC 3 site, and want to use Spring to provide run-time injection of my web service adapters, so that I can stub in mock service calls instead of calling the real deal. 我正在构建一个MVC 3站点,并希望使用Spring来提供我的Web服务适配器的运行时注入,这样我就可以在模拟服务调用中存根而不是调用真正的交易。

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

I've been stung before on Spring thread-safety, where singleton is not "false", so looked at the Spring source to double check that the above was thread safe. 我之前在Spring线程安全方面受到了攻击,其中单例并非“假”,因此请查看Spring源代码以仔细检查以上是否是线程安全的。

The source has this in the comments: 来源在评论中有这个:

/// 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>

My question: why is using this ill-advised? 我的问题:为什么使用这个不明智的? Is it just because of the 2 lines of boiler plate that we don't need? 是不是因为我们不需要两条锅炉板? AFAIK I'm still declaring what object will finally be created in the config, so don't see how it makes it any more tightly coupled? AFAIK我还在声明最终会在配置中创建什么对象,所以不要看它是如何使它更紧密耦合的?

Note: I don't really want to go down the route of using the Spring.Web dll and doing all of my DI through the config, if I can help it! 注意:我真的不想沿着使用Spring.Web dll的路线走下去,通过配置完成我的所有DI,如果我能帮忙的话!

Thanks a lot Duncan 非常感谢邓肯

It's a bad idea because you are not using dependency injection. 这是一个坏主意,因为你没有使用依赖注入。 It's not because of any thread-safety considerations of the GetContext method. 这不是因为GetContext方法的任何线程安全考虑因素。 You are using the service locator pattern which is considered bad practice - the classes should not be responsible from querying the DI container to fetch dependencies, those dependencies should be injected. 您使用的服务定位器模式被认为是不好的做法 - 类不应该负责查询DI容器以获取依赖关系,应该注入这些依赖关系。

As a best practice you should consider writing a custom dependency resolver based on Spring.NET. 作为最佳实践,您应该考虑编写基于Spring.NET的自定义依赖项解析程序 This way dependencies will automatically be injected into controllers and other classes. 这种方式依赖关系将自动注入控制器和其他类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM