Golang中实现依赖注入的方法有以下几种:
type Foo struct {
Dependency *Dependency
}
func NewFoo(dependency *Dependency) *Foo {
return &Foo{
Dependency: dependency,
}
}
type Foo struct {
Dependency *Dependency
}
func (f *Foo) SetDependency(dependency *Dependency) {
f.Dependency = dependency
}
type Dependency interface {
Method()
}
type DependencyImpl struct {}
func (d *DependencyImpl) Method() {}
type Foo struct {
Dependency Dependency
}
func NewFoo(dependency Dependency) *Foo {
return &Foo{
Dependency: dependency,
}
}
type DependencyImpl struct {}
func (d *DependencyImpl) Method() {}
type Foo struct {
Dependency Dependency
}
func NewFoo() *Foo {
return &Foo{}
}
func main() {
container := di.NewContainer()
container.Register(&DependencyImpl{})
container.Register(func(dependency Dependency) *Foo {
return &Foo{
Dependency: dependency,
}
})
foo := container.Resolve((*Foo)(nil)).(*Foo)
}
以上是几种常见的实现依赖注入的方法,根据具体的应用场景和需求可以选择合适的方法。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:delphi ioc依赖注入的方法是什么