Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Types that implement the interface support dynamic bulk injection. #416

Open
zhanjunjie2019 opened this issue Sep 26, 2024 · 0 comments
Open

Comments

@zhanjunjie2019
Copy link


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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant