Setting Up a Container
Understand how to create and configure dependency injection containers in Golang, manage singleton and scoped dependencies, and propagate scoped containers through application contexts to enhance transactional messaging.
We'll cover the following...
We'll cover the following...
To set up a new container, we use the di.New() function to create one and then use either AddSingleton() or AddScoped() to add our dependencies:
container := di.New() container.AddSingleton("db",func(c di.Container) (any, error) {return mono.DB(), nil},)container.AddScoped("tx",func(c di.Container) (any, error) {db := c.Get("db").(*sql.DB)return db.Begin()},)
Setting up a new container
We are choosing to use the short type assertion syntax when we use Get() here. We skip the type assertion checks since they are used so often that simple test runs would reveal problems if the wrong types were used.