Container - Simple Dependency Injection Container
Installation
To install the package, run:
go get github.com/go-zoox/container
Getting Started
import (
"testing"
"github.com/go-zoox/container"
)
func main(t *testing.T) {
container.Register("config", Config.New())
container.Register("logger", Logger.New())
// container.Register("database", Database.New())
container.Register("service.user", UserService.New())
// container.Register("service.post", PostService.New())
}
// config/config.go
package config
import (
cfg "github.com/go-zoox/config"
)
type Config struct {
Database struct {
Host string
Port int
}
Logger struct {
Level string
}
}
func New() *Config {
var c Config
if err := cfg.Load(&c); err != nil {
panic(err)
}
return &c
}
// logger/logger.go
package logger
import (
log "github.com/go-zoox/logger"
)
func New() *log.Logger {
return log.New()
}
// service/user.go
package service
type UserService struct {
Config *Config
Logger *log.Logger
}
func New() *UserService {
return &UserService{
Config: container.MustGet("config").(*Config),
Logger: container.MustGet("logger").(*log.Logger),
}
}
func (u *UserService) GetUser(id int) (*User, error) {
u.Logger.Info("GetUser")
return &User{
ID: id,
Name: "John Doe",
}, nil
}
Inspired by
- vardius/gocontainer - Simple Dependency Injection Container
- golobby/container - A lightweight yet powerful IoC dependency injection container for the Go programming language
- goava/di - 🛠 A full-featured dependency injection container for go programming language
- goioc/di - Simple and yet powerful Dependency Injection for Go
License
GoZoox is released under the MIT License.