Overview
Go-Mojito's dependency injector is part of the core, which enables the easy swap-out of implementations you see in other components. Sadly this means that this component is not dynamically replaceable.
-
System Component
-
Singleton / Transient
-
Not replaceable
-
Supports custom dependencies
You can register custom dependencies with the dependency injector, which will enable them to be automatically available in all your handlers and middleware.
Quick Start
-
Register a custom dependency anywhere in your main file.
mojito.Register(func() *MyType { return &MyType{} }, true) // True tells the dependency injector that this is a singleton dependency -
Create a new Go-Mojito Handler that has a
*MyTypeargument.func SomeHandler(ctx mojito.Context, myType *MyType) {} Go-Mojito will now detect that you want the instance of your custom dependency injected into your handler. If Go-Mojito was unable to link the dependency, you will see error logs when you start up your web app.
FAQ
To register named dependencies, use the mojito.RegisterNamed function that takes a string in addition to the factory function.
mojito.RegisterNamed("MyType", func() *MyType {
return &MyType{}
}, true) // True tells the dependency injector that this is a singleton dependency
To inject a named custom dependency you need to create a context struct which contains the named dependencies you want to use in your handler. By using the `container:"name"` tag, you indicate that you want to resolve by the field's name and not solely by the type.
type HandlerContext struct {
MyType *MyType `container:"name"`
}
func SomeHandler(ctx mojito.Context, handlerCtx *HandlerContext) {}