Thanks for the amazing tutorials. I’ve roughly read the book and checked the source code before actually finished it. One question about the approach of DI in the book which is a bit different with the approach used in RevDev2018. Now I have several questions related to this:
I find that in RevDev2018, you used a DependencyProvider which is a protocol inherited to a few factory protocols but in this book this is not mentioned, even in the single container approach. May I know the reason?
About multi-containers. You initialised an app dependency container in app delegate. It is also the root container. Should I put all the singletons in the root container only? Is root container the only place to init the singletons?
If I would like to have all my containers to live within the whole app life cycle and would like to refer it somewhere else, may I just use global objects instead of putting them all in app delegate?
Hi @fans3210, great to meet you. Sounds great, I’ll try my best to answer your questions below. If I’m not clear on anything or if any new questions pop up please don’t hesitate to ask. Also, apologies for the delay in responding.
We didn’t discuss the provider interface in the book because including it would make the dependency injection chapter very long and we didn’t want to overwhelm folks. We thought about including it but felt that the other topics were slightly more important to cover. The dependency provider interfaces help substitute entire dependency containers which you normally only have to do when running UI or integration tests.
We are currently planning what to include in the book’s next update, if this is something you’d like us to add please let us know. Maybe we can split the chapter in two or something along those lines.
Yes that’s right because the lifetime of the root container should match the lifetime of the app’s process, which is the lifetime you want for singletons. If your root container gets really large you can split the container into multiple roots, there’s no issue with that.
This sounds similar to the service locator pattern. There are definitely tradeoffs when making containers globally accessible. You get ease of use, however you might lose many of the key benefits of dependency injection. Whatever types access a container via a global reference will be harder to unit test. The object under test might only use 10% of the dependency container, yet you’ll need to mock the entire container. For your project this tradeoff might be perfectly fine; I recommend trying both approaches to see which one fits best for you. Having said that, my personal default / preference is to never expose global references.