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

Support interface in As/InvokeAs #81

Open
d-enk opened this issue May 13, 2024 · 1 comment
Open

Support interface in As/InvokeAs #81

d-enk opened this issue May 13, 2024 · 1 comment

Comments

@d-enk
Copy link

d-enk commented May 13, 2024

I suggest using something like:

func canCast[FROM, TO any](soft bool) bool {
	var from FROM
	anyFrom := any(from)

	if anyFrom == nil { // check for interface by reflect
		typeFrom := reflect.TypeOf(&from).Elem()
		typeTo := reflect.TypeOf((*TO)(nil)).Elem()

		toInterface := typeTo.Kind() == reflect.Interface

		return toInterface && typeFrom.Implements(typeTo) ||

			// interface -> not interface - maybe false positive when real FROM not TO
			soft && !toInterface && typeTo.Implements(typeFrom)
	}

	_, ok := anyFrom.(TO)

	return ok
}

instead simply:

var from FROM
_, ok := any(from).(TO)

For As just call canCast[Initial, Alias]

do/di_alias.go

Lines 25 to 26 in 1998a7a

_, ok := any(empty[Initial]()).(Alias)
if !ok {

For InvokeAs apparently need getInstanceType() reflect.Type method

do/service.go

Lines 131 to 133 in 1998a7a

if svc, ok := service.(serviceGetEmptyInstance); ok {
// we need an empty instance here, because we don't want to instantiate the service when not needed
if _, ok = svc.getEmptyInstance().(T); ok {

@d-enk
Copy link
Author

d-enk commented May 13, 2024

soft flag includes checking whether TO type (not interface) can be in FROM interface
looks like a very rare case, but still happens

in case of As you can rely on the provider's error

do/service_alias.go

Lines 161 to 166 in 1998a7a

switch service.getEmptyInstance().(type) {
case Alias:
return service.shutdown(ctx)
default:
return fmt.Errorf("DI: could not cast `%s` as `%s`", s.targetName, s.name)
}

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