Setting Up a Container
Explore how we can set up a new container in our application.
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. ...