dix

package module
v0.3.3 Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2022 License: MIT Imports: 12 Imported by: 8

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

This section is empty.

Types

type Dix

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

func New

func New(opts ...Option) *Dix

New Dix new

func (*Dix) Graph added in v0.3.1

func (x *Dix) Graph() *Graph

func (*Dix) Inject added in v0.3.1

func (x *Dix) Inject(param any, opts ...Option) any

func (*Dix) Option added in v0.3.1

func (x *Dix) Option() Options

func (*Dix) Provide added in v0.3.3

func (x *Dix) Provide(param any)

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 Graph

type Graph struct {
	Objects  string
	Provider string
}

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 {
	// 允许结果为nil
	AllowNil bool
}

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