dix

package module
v0.2.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 11, 2022 License: MIT Imports: 12 Imported by: 7

README

dix

dix是一个参考了dig设计的依赖注入工具

dix和dig的主要区别在于dix能够完成更加复杂的依赖注入管理和namespace依赖隔离

使用

package main

import (
	"fmt"
	"log"
	"os"

	"github.com/pubgo/dix"
	"github.com/pubgo/xerror"
)

type Redis struct {
	Name string
}

type Handler struct {
	Name string
	// 如果是结构体,且tag为dix,那么,会检查结构体内部有指针或者接口属性,然后进行对象注入
	Cli  *Redis `inject:""`
	Cli1 *Redis `inject:"${.Name}"`
}

func main() {
	defer xerror.RecoverAndExit()

	dix.Register(func() *log.Logger {
		return log.New(os.Stderr, "", log.LstdFlags|log.Llongfile)
	})

	dix.Register(func(l *log.Logger) map[string]*Redis {
		l.Println("init redis")
		return map[string]*Redis{
			"default": {Name: "hello"},
		}
	})

	dix.Register(func(l *log.Logger) map[string]*Redis {
		l.Println("init redis")
		return map[string]*Redis{
			"ns": {Name: "hello1"},
		}
	})

	dix.Register(func(r *Redis, l *log.Logger, rr map[string]*Redis) {
		l.Println("invoke redis")
		fmt.Println("invoke:", r.Name)
		fmt.Println("invoke:", rr)
	})

	var h = Handler{Name: "ns"}
	dix.Inject(&h)
	xerror.Assert(h.Cli.Name != "hello", "inject error")
	xerror.Assert(h.Cli1.Name != "hello1", "inject error")
	dix.Invoke()
	fmt.Println(dix.Graph())
}

Documentation

Index

Constants

View Source
const (
	Default = "default"
)

Variables

This section is empty.

Functions

func Graph

func Graph() *graph

Graph dix graph

func Inject added in v0.1.27

func Inject(data interface{}) interface{}

Inject 注入对象

data是指针类型

func Invoke added in v0.1.16

func Invoke()

Invoke 懒执行注册的invoke

执行所有预先注册的invoke

func New

func New(opts ...Option) *dix

New dix new

func Register added in v0.2.0

func Register(data interface{})

Register 注册provider和invoke

invoke没有返回值
provider必须有返回值, 且返回值只能有一个, 类型为map,interface,ptr

Types

type Err added in v0.1.14

type Err struct {
	Err    error
	Msg    string
	Detail string
}

func (Err) Error added in v0.2.0

func (e Err) Error() string

func (Err) String added in v0.2.4

func (e Err) String() string

func (Err) Unwrap added in v0.2.1

func (e Err) Unwrap() error

type Option

type Option func(opts *Options)

func WithTag added in v0.2.3

func WithTag(name string) Option

type Options added in v0.0.9

type Options struct {
	// contains filtered or unexported fields
}

func (Options) Check added in v0.2.0

func (o Options) Check()

Directories

Path Synopsis
example
map

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL