網頁

2023/11/2

Golang uber Fx Parameter Object name tag

Go語言依賴套件uber-go/fxParameter Object name tag用法。


當依賴多個參數類型相同時,可使用Parameter Object搭配name tag來區別,效果同「Golang uber Fx ParamTags, ResultTags name tag」。


範例環境:

  • Go 1.19


事前要求

參考「Golang uber Fx 依賴注入套件 簡單範例」了解Fx基本用法。


範例

main.go

package main

import (
    "fmt"

    "go.uber.org/fx"
)

type S1Param struct {
    fx.In

    S string `name:"s1"`
}

type S1Result struct {
    fx.Out

    S string `name:"s1"`
}

type S2Param struct {
    fx.In

    S string `name:"s2"`
}

type S2Result struct {
    fx.Out

    S string `name:"s2"`
}

func NewString1() S1Result {
    s := string("foo")
    return S1Result{
        S: s,
    }
}

func NewString2() S2Result {
    s := string("bar")
    return S2Result{
        S: s,
    }
}

func main() {
    fx.New(
        fx.Provide(NewString1),
        fx.Provide(NewString2),
        fx.Provide(NewA),
        fx.Invoke(func(a *A) {
            fmt.Println("invoke")
        }),
    ).Run()
}

type A struct {
    S1 string
    S2 string
}

func NewA(s1 S1Param, s2 S2Param) *A {
    fmt.Printf("create A with s1=[%s], s2=[%s]\n", s1.S, s2.S)
    return &A{
        S1: s1.S,
        S2: s2.S,
    }
}

github



測試

執行程式後輸出以下:

[Fx] PROVIDE    string[name = "s1"] <= main.NewString1()
[Fx] PROVIDE    string[name = "s2"] <= main.NewString2()
[Fx] PROVIDE    *main.A <= main.NewA()
[Fx] PROVIDE    fx.Lifecycle <= go.uber.org/fx.New.func1()
[Fx] PROVIDE    fx.Shutdowner <= go.uber.org/fx.(*App).shutdowner-fm()
[Fx] PROVIDE    fx.DotGraph <= go.uber.org/fx.(*App).dotGraph-fm()
[Fx] INVOKE             main.main.func1()
[Fx] RUN        provide: main.NewString1()
[Fx] RUN        provide: main.NewString2()
create A with s1=[foo], s2=[bar]
[Fx] RUN        provide: main.NewA()
invoke
[Fx] RUNNING

沒有留言:

張貼留言