8000 Factory function returning other di.Provide · Issue #51 · d3fvxl/di · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
Factory function returning other di.Provide #51
Open
@matdurand

Description

@matdurand

Sorry for the multiple questions. I did search through the previous issues, but could not find what I was looking for.

I'm trying to have a function that would return a variable number of dependencies to add to the DI container, but where the function also received some dependencies from previously declared di.Provide. I saw this answer which seems to hint that it's possible for a di.Provide to return di.Option, but I cannot make it work.

Here is an example:


type moduleConfig struct {
	di.Inject
	cfg1 string `di:"cfg=m1.v1"`
	cfg2 string `di:"cfg=m2.v1"`
}

func provideModules(cfg moduleConfig) di.Option {
	//imagine some hypothetical conditions to decide which modules to create. 0-n modules can be created
	//using moduleConfig to decide...
	return di.Options(
		di.Provide(m1.NewModule1, di.As(new(component.Module))),
		di.Provide(m2.NewModule2, di.As(new(component.Module))),
	)
}

func startModules(modules []component.Module) error {
    //... do something with the declared modules
    return nil
}

func main() {
	c, err := di.New(
		di.ProvideValue("aaa", di.Tags{"cfg": "m1.v1"}),
		di.ProvideValue("bbb", di.Tags{"cfg": "m2.v1"}),
		di.Provide(provideModules),
	)
	if err != nil {
		panic(err)
	}

	err = c.Invoke(startModules)
	if err != nil {
		panic(err)
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0