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)
}
以上是几种常见的实现依赖注入的方法,根据具体的应用场景和需求可以选择合适的方法。