Skip to content

capabilities akin to Provider / Lazy from dagger #225

Open
@jstncbllr

Description

@jstncbllr

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

It's difficult currently to use wire for conditional bindings or to delay instantiation of a bound type.

I'm thinking along the lines of dagger's support for Provider and Lazy.

Describe the solution you'd like

If wire can inject a type A, it would be cool if it could also inject a func() A. (There's probably a better solution, but without generics, I'm not sure what it would be.)

For example, let's say A is expensive to instantiate, and I only want to do so if some condition is true. This isn't right:

type A struct{
	// expensive things here...
}

var aSet = wire.NewSet(
  wire.Struct(new(A), "*"),
  dependsOnA)

var someCondition bool

func dependsOnA(a A) B {
  // we always pay the cost of instantiating A.
	if someCondition {
		// do stuff with A
	}
	// do other stuff, return a B
}

What one would like is:

func dependsOnA(aProvider func() A) B {
	if someCondition {
    a := aProvider()
		// do stuff with A
	}
	// ...
}

Describe alternatives you've considered

Two alternatives:

  1. Build separate graphs, and use conditions do decide which injector function to use. This isn't great if the dependency graph is complex and there are multiple types that need conditional or lazy instantiation, since configuring the entire graph N different ways is tedious.

  2. Generate separate injector functions for each lazy/conditional thing, and use those functions inside higher level provider functions. Following the example above:

func dependsOnA() B {
	if someCondition {
    a := injectA() // this is a wire gen'd function
		// do stuff with A
	}
	// ...
}

I've used "two injector" strategies in the past (with guice) for bootstrapping, but it's not a great to use use all over the place in an app because you'll have multiple disconnected dependency graphs. This is bad if A needs a B, but B is also needed in a graph elsewhere.

I think some sort of wire analog to Lazy or Provider would also help with #205 and #216

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions