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

Proposal: way to automate invoke deps in do.Provider for any type constructor #67

Open
d-enk opened this issue Apr 26, 2024 · 2 comments
Milestone

Comments

@d-enk
Copy link

d-enk commented Apr 26, 2024

package main

import "github.com/samber/do/v2"


type Type struct {
	int
	uint64
	string
}

func NewType(i int, u uint64, s string) Type {
	return Type{i, u, s}
}


func main() {
	scope := do.New()

	do.ProvideValue(scope, int(1))
	do.ProvideValue(scope, uint64(2))
	do.ProvideValue(scope, string("str"))

	// instead
	do.Provide(scope, func(i do.Injector) (Type, error) {
		return NewType(
			do.MustInvoke[int](i),
			do.MustInvoke[uint64](i),
			do.MustInvoke[string](i),
		), nil
	})

	// something like
	do.ProvideAny[Type](scope, NewType)

	_ = do.MustInvoke[Type](scope)
}

Where

func ProvideAny[T any](i do.Injector, fun any) {
	fn := reflect.ValueOf(fun)
	
	// check that fn is func(...) T or func(...) (T, error)

	do.Provide[T](i, func(i do.Injector) (res T, err error) {
		inputTypes := []reflect.Value{}
		// inputTypes - invoked input by type name

		out := fn.Call(inputTypes)

		// res = out[0]
		// err = out[1]

		return
	})
}

Also the function can have variadic names ... string
With a match for each function parameter, to use it instead of the type name.
Analog do:"name" in struct

If interested I can send pull request.
We can discuss the interface.

Now it just

func ToProvider[T any](fun any) do.Provider[T]

do.Provide(scope, ToProvider[Type](NewType))
@samber
Copy link
Owner

samber commented May 5, 2024

Yes, it has been discussed already.

I'm adding this proposal to v2.1 release.

See #28

@samber samber added this to the v2.1 milestone May 5, 2024
@d-enk
Copy link
Author

d-enk commented May 6, 2024

Yes, it has been discussed already.

There is nothing about calculating constructor function arguments.

Here we are talking about the possibility of turning a "native" constructor into Provider

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

2 participants