drgomesp/cargo
An efficient and robust Go dependency injection container โ by Daniel Ribeiro
Table of Contents
Introduction
cargo is a library that provides a powerful way of handling objects and their dependencies, by using the Container. The container works by implementing the Dependency Injection pattern via constructor injection, resulting in explicit dependencies and the achievement of the Inversion of Control principle.
Installation
$ go get github.com/drgomesp/cargo
How it Works
Builder
The container.Container
is what provides an API to register and retrieve services
Defining services is very simple:
type Foo struct {}
container := container.NewContainer()
container.Register("foo", definition.NewDefinition(&Foo{}))
If you prefer not to use the composite literal expression, you can define a constructor function and use it as a literal:
type Foo struct {}
func NewFoo() *Foo {
return &Foo{}
}
container.Register("foo", definition.NewDefinition(NewFoo))
To check if a service definition exists, simply do:
container.HasDefinition("foo")
And to get a definition back to work with:
if def, err := container.GetDefinition("foo"); err != nil {
fmt.Println(def.ID)
}