rom8726.github.io

di

Minimalistic, reflection-based Dependency Injection (DI) framework for GoLang.

Github: github.com/rom8726/di

Inspired by https://github.com/ivankorobkov/go-di

Features

Installation

go get github.com/rom8726/di

Usage

1. Define your interfaces and implementations

type DBClient interface {
    Exec() (string, error)
}

type Repo interface {
    Find() (string, error)
}

type RepoImpl struct {
    db DBClient
}

func (r *RepoImpl) Find() (string, error) {
    return r.db.Exec()
}

func NewRepo(db DBClient) *RepoImpl {
    return &RepoImpl{db: db}
}

2. Register constructors

c := di.New()
c.Provide(NewRepo)
c.Provide(NewDBClient)

3. Resolve instances

var repo Repo
err := c.Resolve(&repo)
if err != nil {
    log.Fatal(err)
}

4. Inject configuration

params := &MyServiceParams{ParamInt: 42, ParamStr: "hello", ParamBool: true}
c.Provide(NewMyService).Arg(params)

// Or for primitives:
c.Provide(NewMyService2).Args(123, true)

Design Principles

Limitations

Testing

The package includes tests that cover:

go test ./...