Using the Context
Introduction
Now that you are familiar with the concepts and the basis to create the context it makes sense to explore what are the benefits os using dependency injection.
Benefits
Reduce boilerplate
One of the major advantages of dependency injection is that it lets you code your components not worrying about how to wire them together
You just write the classes and functions that you are going to use so that they receive as normal whichever parameters you need them to receive.
By not having to create the objects explicitly you will already reducing the boilerplate.
Centralise Configuration
Having a single point where all beans share their dependencies is very handy, it makes very simple to change the configuration for the entire application and to cascade changes.
Having centralised configuration also helps reducing boiler plate code, is very likely that you will share a lot of dependencies through all the beans you need to create.
As long as you hint them using the same name, you will only need to specify then once.
Helps decoupling your components
By using dependency injection your are NOT going to automatically start to have your components more decoupled, but it will empower you to do so.
For instance, one common decoupling pattern is the strategy pattern
You could use this pattern not using dependency injection, but you would likely be overwhelmed by the amount of wiring if your were to do it yourself.
Your application interface
When thinking about the beans you want to expose through the context, it is helpful to think of them as the interface for your entire application.
This can help you, or other members of your team to develop further components, as you can then leverage the context as if it was the API to provide as the foundation.
Obviously then, as you add more beans to your context, you will also be expanding your API
Helps with integration testing
Derived from all the benefits mentioned already, dependency injection lets you easily write integrations tests.
To be able to fully benefit from this, you are likely going to have to change your context before you run your tests.
Doing so, lets you stub/mock complex dependencies and substitute them for integration testing.
Last updated