go-inject is a dependency injection library that support contextual scope.
package myapp
import (
"context""github.com/illuin-tech/goinject"
)
typekeyintconstmyScopeKeykey=0constMyScope="MyScope"// define function to declare your own scope in contextfuncWithMyScopeEnabled(ctx context.Context) context.Context {
returngoinject.WithContextualScopeEnabled(ctx, myScopeKey)
}
funcShutdownMyContextScoped(ctx context.Context) {
goinject.ShutdownContextualScope(ctx, myScopeKey)
}
// define injection modulesvarModule=goinject.Module("myModule",
goinject.RegisterScope(MyScope, goinject.NewContextualScope(myScopeKey)),
goinject.Provide(func() string {
return"Hello world from scope"
}, goinject.In(MyScope)),
)
funcmain() {
ctx:=context.Background()
// enable scopectx=WithMyScopeEnabled(ctx)
deferShutdownMyContextScoped(ctx)
injector, _:=goinject.NewInjector(Module)
_=injector.Invoke(ctx, func(hellostring) {
println(hello) })
}