Dependency injection in Golang at runtime.
Make sure that Go is installed on your computer. Type the following command in your terminal:
go get github.com/asaskevich/godi
or you can get specified release of the package with gopkg.in
:
go get gopkg.in/asaskevich/godi.v1.0.0
After it the package is ready to use.
Add following line in your *.go
file:
import "github.com/asaskevich/godi"
To start you need to create structs (like services) or factory functions.
Be sure to use tag godi
on struct fields that will be used for the dependency injection.
type Repository struct {
Driver CustomDriver `godi:"autowire"`
Print Printer `godi:"autowire"`
}
type CustomDriver struct {
Name string
}
type Printer struct {
// fields
}
...
c := Container{}
c.New()
c.RegisterService(CustomDriver{Name:"my_driver"})
c.RegisterFactory(func () Printer {
// init Printer
return Printer{}
})
service, err := c.ConstructService(Repository{})
println(service.(Repository).Driver.Name) // "my_driver"
type Container
func (c *Container) ConstructService(item interface{}) (interface{}, error)
func (c *Container) GetFactory(factoryType string) (func() interface{}, error)
func (c *Container) GetService(serviceType string) (interface{}, error)
func (c *Container) HasFactory(service interface{}) (res bool)
func (c *Container) HasService(item interface{}) (res bool)
func (c *Container) New()
func (c *Container) RegisterFactory(service func() interface{})
func (c *Container) RegisterService(item interface{})
Note: without the tag inner structures will not be created
-
- to skip processing fieldautowire
- allows building inner service automatically
Documentation is available here: godoc.org. Full information about code coverage is also available here: godi on gocover.io.
If you do have a contribution to the package, feel free to create a Pull Request or an Issue.
If you don't know what to do, there are some features and functions that need to be done
- Refactor code
- Edit docs and README: spellcheck, grammar and typo check
- Resolve issues and bugs
- Look at forks for new features and fixes
- Dependency injection by sub-type
- Resolve dependency conflicts (e.g. two types matched one common type)
- Qualifiers to define custom Id of service
- Autoscan
- Separate services into repositores/components/services/controllers
- Autowire string/int properties from files