Dependency Injection for Modules Using Containers
Explore how to apply dependency injection with containers in Golang modules to improve transactional messaging. Understand how to manage singleton and scoped dependencies, including setting up transactions and using interfaces for flexible database interactions in event-driven architecture.
We will dive into a module to switch its composition root over to using the DI containers.
Using the di package in each of the modules is going to be the same, but for the examples of what needs to be updated, we are going to use the Depot module. We have chosen the Depot module because it uses every kind of event and message handler.
Container setup
We first create a new container at the start of the composition root Startup() method, like so:
func (Module) Startup(ctx context.Context, mono monolith.Monolith) (err error) {container := di.New()// ...}
In the composition root, we will tackle the changes in three parts. First, the driven adapters need to be divided up into singleton and scoped dependencies. Then, the application and handlers need to be made into dependencies. Finally, we will update ...