Documentation
¶
Overview ¶
Package di provides a dependency container where all dependencies can be registered and cached with different lifetime scope. It adds validation for common mistakes like missing or cyclic dependency. Container allows to provide service implementation without knowing how to construct it. The container is responsible for caching, managing dependencies and creating the objects.
Example ¶
package main
import (
"fmt"
"github.com/Prastiwar/Go-flow/di"
)
type Dependency interface{}
type someDependency struct{} // implements Dependency
func NewSomeDependency() *someDependency {
return &someDependency{}
}
type SomeInterface interface{}
type someService struct { // implements SomeInterface
serv Dependency
}
func NewSomeService(serv Dependency) *someService {
return &someService{
serv: serv,
}
}
func main() {
// register constructors for services and dependencies. By default all services are transient
container, err := di.Register(
NewSomeService,
NewSomeDependency,
)
// alternatively you can setup lifetime
// container, err := di.Register(
// di.Construct(di.Singleton, NewSomeService),
// di.Construct(di.Transient, NewSomeDependency),
// di.Construct(di.Scoped, NewSomeDependency),
// )
if err != nil {
// each ctor must be func Kind with single output parameter
panic(err)
}
// di.Register() already calls this validation - you don't need to do it again
err = container.Validate()
if err != nil {
// any service couldn't be created due to missing or cyclic dependencies
panic(err)
}
// use container.Scope() to create new scoped container which caches scoped services
// scopedContainer := container.Scope()
var s SomeInterface
fmt.Println(s == nil)
// panics when there is not service implementing SomeInterface
container.Provide(&s)
fmt.Println(s == nil)
}
Output: true false
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrCtorNotFunc = errors.New("ctor is not func") ErrWrongCtorSignature = errors.New("ctor must return only service value") )
Functions ¶
func Construct ¶
Construct returns a new constructor instance for specified function. It panics if ctor is not a function or it does not return any value.
func NewRootCache ¶
func NewRootCache() *rootCache
NewRootCache returns a new Cache which is defined as root and will cache Singleton services.
func NewScopeCache ¶
func NewScopeCache(root Cache) *scopeCache
NewScopeCache returns a new Cache which is defined as scope for specified root Cache. Can store both Singleton and Scoped LifeTime services.
Types ¶
type Cache ¶
type Cache interface {
Get(LifeTime, reflect.Type) (interface{}, bool)
Put(LifeTime, reflect.Type, interface{}) bool
}
Cache is implemented by any value that has a Get and Put method. The implementation controls where and how reflect.Type is stored for specified LifeTime.