views:

155

answers:

2

I'm wondering how I should store/reference my dependency injection container(s). Is it alright to have a container be a static property on a static class? Or should I have the container be an instance variable on the application? I'm wondering what the pros and cons of each option are, and what is the best practice for this in web, mvc, console, and windows apps?

+2  A: 

I recommend storing it as an instance variable on the application. Using a static property - making it a globally accessible singleton - hides your application's dependency on it, which is one of the things you're trying to get away from by using a dependency injection container in the first place!

Having said that, if your framework makes it difficult for you to access your application instance, it wouldn't be the end of the world to use a static variable.

Jeff Sternal
+1  A: 

I agree with Mr. Sternal on this. One thing to consider is that some DI containers implement IDisposable, so you probably want to dispose of the container on normal program termination. See How do you reconcile IDisposable and IoC?

Also note that it's often best to avoid scattering dependencies on the DI container throughout your application. In other words, try to avoid making the container globally available (Singleton, static property, or even injected) to use as a Service Locator.

Instead, you can use the container's ability to resolve dependencies of dependencies. For instance, you might create the container at application startup and use it to construct your Model (in MVC). The model might depend on a repository and a web service. The repository might depend on a logger. The container will resolve all of these when the model is constructed. If your model needs to create instances of dependencies on the fly, inject a factory into it.

TrueWill
Agreed, and I like how one poster put it in one of the dupes Mauricio dug up: "Put the IOC container at the highest level / entry point in the process and use it to inject dependencies in everything underneath it." (http://stackoverflow.com/questions/480286/best-practices-for-ioc-container)
Jeff Sternal
@Jeff - Nice quote; simple and to the point. There's also an excellent answer by Thorsten Lorenz in this link (also from Mauricio):http://stackoverflow.com/questions/480286/best-practices-for-ioc-container
TrueWill