Where should I store a reference to my DI container?
E

2

11

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?

Eudemonics answered 17/11, 2009 at 2:6 Comment(2)
duplicate: #645247 #277938 #480786 #367678 #1613182Rabi
Thanks everyone! Sorry for all the duplicates - I figured this was a dup but wasn't sure how to phrase my question to find them.Eudemonics
B
7

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.

Bookplate answered 17/11, 2009 at 2:23 Comment(0)
F
2

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.

Fawcett answered 17/11, 2009 at 2:46 Comment(3)
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." (#480786)Bookplate
@Jeff - Nice quote; simple and to the point. There's also an excellent answer by Thorsten Lorenz in this link (also from Mauricio): #480786Fawcett
If you put the container at the highest level, this presumably creates a need to hold a reference to your lowest level assembly which requires injection (data access perhaps). This irks me a little :(Earing

© 2022 - 2024 — McMap. All rights reserved.