简体   繁体   中英

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.

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.

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?

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!

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

As a best practice you should consider writing a custom dependency resolver based on Spring.NET. This way dependencies will automatically be injected into controllers and other classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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