dix

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jun 20, 2022 License: MIT Imports: 10 Imported by: 9

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

This section is empty.

Variables

This section is empty.

Functions

func Graph

func Graph() *graph

Graph dix graph

func Inject added in v0.1.27

func Inject[T any](data T, opts ...Option) T

Inject 注入对象

data是<*struct>或者<func>

func New

func New(opts ...Option) *dix

New dix new

func Provider added in v0.1.24

func Provider(data any)

Provider 注册provider

provider必须有返回值, 且返回值只能有一个, 类型为map,any,ptr,slice,func

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 AllowNil added in v0.2.12

func AllowNil() 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