samber / do

⚙️ A dependency injection toolkit based on Go 1.18+ Generics.
https://pkg.go.dev/github.com/samber/do
MIT License
1.82k stars 75 forks source link

How can I InvokeNamed T to any #60

Closed iyaozhen closed 4 months ago

iyaozhen commented 7 months ago

Demo(use v2):

func TestInvokeAny(t *testing.T) {
    do.ProvideNamed(nil, "test", func(i do.Injector) (int, error) {
        return 1, nil
    })

    int1, err := do.InvokeNamed[int](nil, "test")
    if err != nil {
        t.Errorf("invoke error: %v", err)
        return
    }
    if int1 != 1 {
        t.Errorf("invoke response error: %v", int1)
        return
    }
    int2, err := do.InvokeNamed[any](nil, "test")
    if err != nil {
        t.Errorf("invoke error: %v", err)
        return
    }
    t.Log(int2)
}

do.InvokeNamed[any](nil, "test") not work

image

Why do I have to do this?

I want to generic call my local service, I just known service name

localService, err := do.InvokeNamed[any](nil, "ServiceName")
if err != nil {
return nil, err
}
methodValue := reflect.ValueOf(localService).MethodByName("FuncName")

invokeAnyByName Is what I want, can you Export It ?

thank you

samber commented 7 months ago

This is embarrassing. 🫣

Let me think about it.

d-enk commented 5 months ago

Аlso came across this

Seems to be solved by adding (Must)InvokeAsNamed to support not only any.

It just invokeAnyByName().(T), but with cast check in package

samber commented 5 months ago

I suppose do.InvokeNamed() should be able to skip the type check when the type is any ?

iyaozhen commented 5 months ago

I suppose do.InvokeNamed() should be able to skip the type check when the type is any ?

I think this is a good solution.

samber commented 4 months ago

@d-enk in your PR you said we might add the behavior to AsNamed. Can you tell us more about your though?

I don't see in what case we would declare an alias to any.

d-enk commented 4 months ago

I assumed. I just look at where invokeByName (type check) is used. https://github.com/samber/do/blob/1998a7a1b1a618eed087c91bc4932934355d5477/service_alias.go#L78-L79 No more reasons. Of course, it doesn't make sense until it's needed.

Thanks for the approval before 2.0

samber commented 4 months ago