Skip to content

demoManito/inject

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

16 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Inject (golang dependency injection)

About Inject

inject is a simple dependency injection library for Go. based on tag inject to inject dependencies into struct fields.

Quick Start

  • dao/dao.go
package dao

import (
	"database/sql"

	"github.com/demoManito/inject"
)

func init() {
	inject.Register(func(injector inject.Injector) error {
		injector.Register("db", &sql.DB{})
		injector.Register("dao", &Dao{})
		return nil
	})
}

type Dao struct {
	DB *sql.DB `inject:"db"`
}
  • service/service.go
package service

import (
	"github.com/demoManito/inject"

	"github.com/xxx/xxx/dao"
)

func init() {
	inject.Register(func(injector inject.Injector) error {
		injector.Register("service", &Service{})
		return nil
	})
}

type Service struct {
	Dao *dao.Dao `inject:"dao"`
}
  • main.go
package main

import (
	"database/sql"

	"github.com/demoManito/inject"
	"github.com/demoManito/inject/injector"

	"github.com/xxx/xxx/service"
)

type Handler struct {
	Service *service.Service `inject:"service"`
}

func main() {
	hanlder := &Handler{}
	
	// choose one of the following methods:
	// concurrency safe
	inject.New(injector.New()).Inject(handler)
	// concurrency unsafe, but faster
	inject.New(injectorv2.New()).Inject(handler)

	// eg: use handler, private fields can also be injected
	handler.Service.Dao.DB.Ping()
}

Easy Example

Easy Example

About

simple dependency injection library for Go

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages