wire icon indicating copy to clipboard operation
wire copied to clipboard

Types that implement the interface support dynamic bulk injection.

Open zhanjunjie2019 opened this issue 1 year ago • 0 comments


name: zhanjunjie about: Suggest an idea for this project


Is your feature request related to a problem? Please describe.

There is an interface definition, and several implementation classes that implement this interface. In the constructor of another implementation class, all known instances of the implemented types need to be injected into this interface in the form of an array. The code is as follows:

// Interface and Implementation Class

type IAbs interface {
	Print()
}

type FirstAbsImpl struct {
}

func (f FirstAbsImpl) Print() {
	fmt.Println("I am FirstAbsImpl")
}

type SecondAbsImpl struct {
}

func (s SecondAbsImpl) Print() {
	fmt.Println("I am SecondAbsImpl")
}

// App

type App struct {
	abs []IAbs
}

func (a App) Prints() {
	for _, ab := range a.abs {
		ab.Print()
	}
}

Describe the solution you'd like

I hope to avoid the need to specify a particular location to track all the constructors of implementation classes. Instead, I would like the implementation classes to register themselves and allow injection in the form of an array or any single instance type.

Describe alternatives you've considered

// Interface and Implementation Class

var abs []IAbs

type IAbs interface {
	Print()
}

func init() {
	abs = append(abs, &FirstAbsImpl{})
}

type FirstAbsImpl struct {
}

func (f FirstAbsImpl) Print() {
	fmt.Println("I am FirstAbsImpl")
}

func init() {
	abs = append(abs, &SecondAbsImpl{})
}

type SecondAbsImpl struct {
}

func (s SecondAbsImpl) Print() {
	fmt.Println("I am SecondAbsImpl")
}

// App

type App struct {
}

func (a App) Prints() {
	for _, ab := range abs {
		ab.Print()
	}
}

Additional context

Add any other context or screenshots about the feature request here.

zhanjunjie2019 avatar Sep 26 '24 08:09 zhanjunjie2019