DI
:
-
go get -u github.com/MaximZayats/godi/
-
import "github.com/MaximZayats/godi/di"
CMD
:
-
go get -u github.com/MaximZayats/godi/cmd/godi
-
go run github.com/MaximZayats/godi/cmd/godi init ./storage/decorators
-
go run github.com/MaximZayats/godi/cmd/godi --help
-
Simple: Getting from container
package main import ( "fmt" "github.com/MaximZayats/godi/di" ) func main() { di.AddSingletonByFactory[float32](func(c *di.Container) float32 { return 11.22 }) di.AddInstance[int](123) di.AddByFactory[string](func(c *di.Container) string { return "aabbcc" }) fmt.Println(di.Get[int]()) // 123 fmt.Println(di.Get[string]()) // "aabbcc" fmt.Println(di.Get[float32]()) // 11.22 fmt.Println(di.Get[float32]()) // 11.22 }
-
Injection: Pass arguments to function (Simple code generation is required)
Full code: godi-fiber-example
Snippet:
type H = func(*fiber.Ctx) error // `stringFromDI` will be injected into the handler func handler(c *fiber.Ctx, stringFromDI string) error { return c.SendString("Hello from di: " + stringFromDI) } func main() { di.AddInstance[string]("I'm string from DI!!!", c) ... app.Get("/", injection.Inject[H](handler)) }
-
Getting from container:
- See examples above
-
Injection (decorating):
- Generate package for storing decorators:
-
go run github.com/MaximZayats/godi/cmd/godi init ./storage/decorators
- Configure
godi.injection
:-
import ( ".../storage/decorators" "github.com/MaximZayats/godi/injection" ) injection.Configure(decorators.Config)
-
- Use injection:
-
See full example
// `a` and `b` will be auto injected in the function func Handler(c context.Context, a int, b string) int { fmt.Println(c, a, b) return a } injection.Configure(decorators.Config) // H is the type alias for the function after injection type H = func(context.Context) int decoratedHandler := injection.Inject[H](Handler) // IMPORTANT! You need to verify injection injection.MustVerifyInjections() decoratedHandler(context.TODO())
-
-
- Generate package for storing decorators:
goos: windows
goarch: amd64
pkg: github.com/MaximZayats/godi/benchmark
cpu: AMD Ryzen 5 1600 Six-Core Processor
BenchmarkGetFromFactorySingleton
BenchmarkGetFromFactorySingleton-12 500488393 2.443 ns/op
BenchmarkGetInstance
BenchmarkGetInstance-12 495795447 2.403 ns/op
BenchmarkGetFromFactory
BenchmarkGetFromFactory-12 361722957 3.273 ns/op
PASS