Documentation ¶
Overview ¶
Exports the methods of a global instance to simplify the use of the lib
Index ¶
- Constants
- Variables
- func AllOf[T any](c Container, ctx context.Context) (o []T, e error)
- func AllOfFilter[T any](filter *FilteredFactories, ctx context.Context) (o []T, e error)
- func Alternative(f *Factory)
- func Contains(key reflect.Type) bool
- func ContainsRecursive(key reflect.Type) bool
- func DefaultFactorySortLessFn(a, b *Factory) bool
- func Destroy() error
- func DestroyObject(key reflect.Type, object any) error
- func DestroySingletons() error
- func Get[T any](ctx ...context.Context) (o T, e error)
- func GetFrom[T any](c Container, contexts ...context.Context) (o T, e error)
- func Initialize(ctx ...context.Context) error
- func Injected[T any](opts ...FactoryConfig)
- func InjectedTo[T any](c Container, opts ...FactoryConfig)
- func Injector[T any]() func(Container, context.Context) (out T, err error)
- func Key[T any]() reflect.Type
- func KeyOf(t any) reflect.Type
- func Mock(mock any) (cleanup func())
- func MustGetFrom[T any](c Container, ctx ...context.Context) T
- func Primary(f *Factory)
- func Prototype(f *Factory)
- func Register(ctor any, opts ...FactoryConfig)
- func RegisterScope(name string, scope ScopeI) error
- func ResolveArgs(factory *Factory, ctx ...context.Context) ([]reflect.Value, error)
- func ShouldRegister(ctor any, opts ...FactoryConfig) error
- func Singleton(f *Factory)
- type AlternativeQualifier
- type Callback
- type ConditionFunc
- type Container
- type CreateObjectFunc
- type Disposable
- type DisposableAdapter
- type Factory
- func (f *Factory) Alternative() bool
- func (f *Factory) Conditions() []ConditionFunc
- func (f *Factory) Constructor() reflect.Value
- func (f *Factory) Create(args []reflect.Value) (any, error)
- func (f *Factory) Disposers() []Callback
- func (f *Factory) HasConditions() bool
- func (f *Factory) HasDisposers() bool
- func (f *Factory) HasQualifier(q reflect.Type) bool
- func (f *Factory) Id() int
- func (f *Factory) IsTrueSingleton() bool
- func (f *Factory) Key() reflect.Type
- func (f *Factory) Mock() bool
- func (f *Factory) Name() string
- func (f *Factory) Order() int
- func (f *Factory) Params() []reflect.Type
- func (f *Factory) Primary() bool
- func (f *Factory) Prototype() bool
- func (f *Factory) Qualifiers() []reflect.Type
- func (f *Factory) ReturnErrorIdx() int
- func (f *Factory) ReturnValueIdx() int
- func (f *Factory) ReturnsError() bool
- func (f *Factory) ReturnsValue() bool
- func (f *Factory) Scope() string
- func (f *Factory) Singleton() bool
- func (f *Factory) Startup() bool
- func (f *Factory) Type() reflect.Type
- type FactoryConfig
- func Condition(condition ConditionFunc) FactoryConfig
- func Disposer[T any](disposer func(T)) FactoryConfig
- func Initializer[T any](initializer func(T)) FactoryConfig
- func Order(order int) FactoryConfig
- func Qualify[Q any]() FactoryConfig
- func Scoped(scope string) FactoryConfig
- func Startup(order int) FactoryConfig
- func Stereotype(options ...FactoryConfig) FactoryConfig
- type FilteredFactories
- type Initializable
- type IntectorFn
- type Parameter
- func (p *Parameter) Candidates() (list []*Factory)
- func (p *Parameter) Factories() (list []*Factory)
- func (p *Parameter) HasCandidates() bool
- func (p *Parameter) IsValidCandidate(f *Factory) (isCandidate bool, isExactMatch bool)
- func (p *Parameter) Key() reflect.Type
- func (p *Parameter) Provider() bool
- func (p *Parameter) Qualified() bool
- func (p *Parameter) Qualifier() reflect.Type
- func (p *Parameter) Unmanaged() bool
- func (p *Parameter) Value() reflect.Type
- func (p *Parameter) ValueOf(value any) reflect.Value
- type PrimaryQualifier
- type Provider
- type Qualified
- type ScopeI
- type TypeBase
- type Unmanaged
Constants ¶
const ( SCOPE_SINGLETON string = "singleton" SCOPE_PROTOTYPE string = "prototype" )
Variables ¶
var ( ErrCycleDetected = errors.New("this component introduces a cycle") ErrManyCandidates = errors.New("multiple candidates found") ErrContainerLocked = errors.New("container is locked") ErrContextRequired = errors.New("context required") ErrInvalidProvider = errors.New("invalid provider") ErrMissingDependency = errors.New("missing dependencies") ErrCandidateNotFound = errors.New("no candidate found") ErrNoScopeNameDefined = errors.New("no scope name defined for component") ErrCurrentlyInCreation = errors.New("requested component is currently in creation") ErrNoScopeNameRegistered = errors.New("no Scope registered") )
var ErrNotStruct = errors.New("the Injected method only accepts struct or *struct")
Functions ¶
func AllOfFilter ¶
func AllOfFilter[T any](filter *FilteredFactories, ctx context.Context) (o []T, e error)
func Alternative ¶
func Alternative(f *Factory)
Alternative indicates that a component should NOT be given preference when multiple candidates are qualified to inject a single-valued dependency.
If exactly one NON-ALTERNATIVE component exists among the candidates, it will be the injected value.
Example:
di.Register(func(repository FooRepository) FooService { return &FooServiceImpl{ repository: repository } }) di.Register(func() FooRepository { return &MemoryRepositoryImpl{} }) di.Register(func() FooRepository { return &DatabaseRepositoryImpl{} }, di.Alternative)
Because DatabaseRepositoryImpl is marked with Alternative, it will NOT be injected over the MemoryRepositoryImpl variant assuming both are present as component within the same di container.
func Contains ¶
Contains check if this container contains a component with the given key. Does not consider any hierarchy this container may participate in.
func ContainsRecursive ¶
func DefaultFactorySortLessFn ¶
DefaultFactorySortLessFn is the default sorting function used by the Filter method, which sorts the factories in the following order:
1) Mock (test) 2) Primary 3) NOT Alternative 4) Lower Order
func DestroyObject ¶
DestroyObject destroy the given instance
func DestroySingletons ¶
func DestroySingletons() error
DestroySingletons destroy all singleton components in this container. To be called on shutdown of a factory.
func Initialize ¶
Initialize initialize all non-lazy singletons (startup)
func Injected ¶
func Injected[T any](opts ...FactoryConfig)
Injector simplifies component registration through reflection.
Example:
type myController struct { MyService Service `inject:""` } di.Injected[*myController]()
In the example above, the MyService dependency will be injected automatically.
func InjectedTo ¶ added in v0.0.6
func InjectedTo[T any](c Container, opts ...FactoryConfig)
Injector simplifies component registration through reflection.
Example:
type myController struct { MyService Service `inject:""` } di.InjectedTo[*myController](di.Global())
In the example above, the MyService dependency will be injected automatically.
func Injector ¶ added in v0.0.6
Injector simplifies component registration through reflection.
Example:
type myController struct { MyService Service `inject:""` } di.Register(di.Injector[*myController]())
In the example above, the MyService dependency will be injected automatically.
@TODO: embedded structs
func Mock ¶
func Mock(mock any) (cleanup func())
Mock test only, register a mock instance to the container
func MustGetFrom ¶
MustGetFrom get a instance from container using generics (panic on error)
func Primary ¶
func Primary(f *Factory)
Primary indicates that a component should be given preference when multiple candidates are qualified to inject a single-valued dependency. If exactly one 'primary' component exists among the candidates, it will be the injected value.
Example:
di.Register(func(repository FooRepository) FooService { return &FooServiceImpl{ repository: repository } }) di.Register(func() FooRepository { return &MemoryRepositoryImpl{} }) di.Register(func() FooRepository { return &DatabaseRepositoryImpl{} }, di.Primary)
Because DatabaseRepositoryImpl is marked with Primary, it will be injected preferentially over the MemoryRepositoryImpl variant assuming both are present as component within the same di container.
func Prototype ¶
func Prototype(f *Factory)
Prototype identifies a component that a new instance is created every time the component factory is invoked.
Example:
di.Register(func() MyService { return &MyServiceImpl{ Id: uuid.New() } }, di.Prototype) di.Register(func(s MyService) MyControllerA { print(s.Id) // first uuid }) di.Register(func(s MyService, ctn di.Container, ctx context.Context) MyControllerB { print(s.Id) // second uuid s2, _ := di.Get[testService](ctn, ctx) print(s2.Id) // third uuid })
func Register ¶
func Register(ctor any, opts ...FactoryConfig)
func RegisterScope ¶
RegisterScope Register the given scope, backed by the given ScopeI implementation.
func ResolveArgs ¶
ResolveArgs returns an ordered list of values which may be passed directly to the Factory Create method
func ShouldRegister ¶
func ShouldRegister(ctor any, opts ...FactoryConfig) error
func Singleton ¶
func Singleton(f *Factory)
Singleton identifies a component that only instantiates once.
Example:
di.Register(func() MyService { return &MyServiceImpl{ Id: uuid.New() } }, di.Singleton) di.Register(func(s MyService) MyControllerA { print(s.Id) // uuid value }) di.Register(func(s MyService) MyControllerB { print(s.Id) // same uuid value })
Types ¶
type AlternativeQualifier ¶
type AlternativeQualifier uint8
type ConditionFunc ¶
type Container ¶
type Container interface { // Initialize initialize all non-lazy singletons (startup) Initialize(ctx ...context.Context) error Register(ctor any, opts ...FactoryConfig) ShouldRegister(ctor any, opts ...FactoryConfig) error // RegisterScope Register the given scope, backed by the given ScopeI implementation. RegisterScope(name string, scope ScopeI) error // Get return an instance, which may be shared or independent, of the specified component. Get(key reflect.Type, ctx ...context.Context) (any, error) // Contains check if this container contains a component with the given key. // Does not consider any hierarchy this container may participate in. Contains(key reflect.Type) bool ContainsRecursive(key reflect.Type) bool Filter(options ...FactoryConfig) *FilteredFactories GetObjectFactory(factory *Factory, managed bool, ctx ...context.Context) CreateObjectFunc GetObjectFactoryFor(key reflect.Type, managed bool, ctx ...context.Context) CreateObjectFunc // ResolveArgs returns an ordered list of values which may be passed directly to the Factory Create method ResolveArgs(factory *Factory, ctx ...context.Context) ([]reflect.Value, error) // Destroy this container Destroy() error // DestroyObject destroy the given instance DestroyObject(key reflect.Type, object any) error // DestroySingletons destroy all singleton components in this container. To be called on shutdown of a factory. DestroySingletons() error // Mock test only, register a mock instance to the container Mock(mock any) (cleanup func()) }
type CreateObjectFunc ¶
type CreateObjectFunc func() (any, DisposableAdapter, error)
func GetObjectFactory ¶
func GetObjectFactory(factory *Factory, managed bool, ctx ...context.Context) CreateObjectFunc
func GetObjectFactoryFor ¶
type Disposable ¶
type Disposable interface {
// Destroy invoked by the container on destruction of a component.
Destroy()
}
Disposable interface to be implemented by components that want to release resources on destruction
See Disposer
type DisposableAdapter ¶
DisposableAdapter adapter that perform various destruction steps on a given component instance:
type Factory ¶
type Factory struct {
// contains filtered or unexported fields
}
Factory is a node in the dependency graph that represents a constructor provided by the user and the basic attributes of the returned component (if applicable)
func (*Factory) Alternative ¶
Alternative returns true if this is a Alternative candidate for a component (has the qualifier AlternativeQualifier)
func (*Factory) Conditions ¶
func (f *Factory) Conditions() []ConditionFunc
Conditions returns the list of conditions methods for this factory The component is only eligible for registration when all specified conditions match.
func (*Factory) Constructor ¶
func (*Factory) HasConditions ¶
HasConditions returns true if this factory has any condition method
func (*Factory) HasDisposers ¶
HasDisposers returns true if this factory has any disposer method
func (*Factory) HasQualifier ¶
HasQualifier return true if this Factory has the specified qualifier
func (*Factory) IsTrueSingleton ¶
IsTrueSingleton returns true if is a reference for a singleton instance
func (*Factory) Order ¶
Order the order value of this factory
Higher values are interpreted as lower priority. As a consequence, the object with the lowest value has the highest priority.
Same order values will result in arbitrary sort positions for the affected objects.
func (*Factory) Primary ¶
Primary returns true if this is a Primary candidate for a component (has the qualifier PrimaryQualifier)
func (*Factory) Qualifiers ¶
Qualifiers returns the list of qualifiers for this factory
func (*Factory) ReturnErrorIdx ¶
func (*Factory) ReturnValueIdx ¶
func (*Factory) ReturnsError ¶
func (*Factory) ReturnsValue ¶
type FactoryConfig ¶
type FactoryConfig func(*Factory)
FactoryConfig is the type to configure the component Factory. Container.Register accepts any number of config (this is functional option pattern).
func Condition ¶
func Condition(condition ConditionFunc) FactoryConfig
Condition a single condition that must be matched in order for a component to be registered. Conditions are checked immediately before the component factory is due to be registered and are free to veto registration based on any criteria that can be determined at that point.
func Disposer ¶
func Disposer[T any](disposer func(T)) FactoryConfig
Disposer register a disposal function to the component. A factory component may declare multiple disposer methods. If the factory returns nil, the disposer will be ignored
See Disposable
func Initializer ¶
func Initializer[T any](initializer func(T)) FactoryConfig
Initializer register a initializer function to the component. A factory component may declare multiple initializers methods. If the factory returns nil, the initializer will be ignored
See Initializable
func Order ¶
func Order(order int) FactoryConfig
Order can be applied to any component to indicate in what order they should be used.
Higher values are interpreted as lower priority. As a consequence, the object with the lowest value has the highest priority.
Same order values will result in arbitrary sort positions for the affected objects.
If the component is marked as Startup, the order determines its execution order.
Order is also used during dependency injection. The candidate with the lower order will be injected.
A framework can implement filters and use order to define the order of execution
func Qualify ¶
func Qualify[Q any]() FactoryConfig
Qualify register a qualifier for the component. Anyone can define a new qualifier.
Example:
type MyQualifier string di.Register(func() *MyService { return &MyService{} }, di.Qualify[testQualifier]())
func Scoped ¶
func Scoped(scope string) FactoryConfig
Scoped identifies the lifecycle of an instance, such as singleton, prototype, and so forth.. A scope governs how the container reuses instances of the type.
To register additional custom scopes, see Container.RegisterScope.
Defaults to an empty string ("") which implies SCOPE_SINGLETON.
func Startup ¶
func Startup(order int) FactoryConfig
Startup indicates that this component must be initialized during container initialization (Container.Initialize method)
Example:
di.Register(func() { print("Second") }, Startup(200)) di.Register(func() { print("First") }, Startup(100))
func Stereotype ¶
func Stereotype(options ...FactoryConfig) FactoryConfig
Stereotype a stereotype encapsulates any combination of ComponentOption
Example:
var Controller = di.Stereotype(di.Singleton, di.Qualify[testQualifier](), di.Startup(500)) di.Register(func() MyController { return &MyController{} }, Controller)
Example: Filter using Stereotype
di.Filter(Controller).Foreach(func(f *Factory) (bool, error) { ... })
type FilteredFactories ¶
type FilteredFactories struct {
// contains filtered or unexported fields
}
func Filter ¶
func Filter(options ...FactoryConfig) *FilteredFactories
func FilterOf ¶
func FilterOf[T any](c Container) *FilteredFactories
func (*FilteredFactories) Foreach ¶
func (f *FilteredFactories) Foreach(visitor func(f *Factory) (stop bool, err error)) error
func (*FilteredFactories) Instances ¶
func (f *FilteredFactories) Instances(ctx context.Context) ([]any, error)
func (*FilteredFactories) Sort ¶
func (f *FilteredFactories) Sort(less func(a, b *Factory) bool) *FilteredFactories
type Initializable ¶
type Initializable interface {
// Initialize invoked by the container on creation of a component.
Initialize()
}
Initializable interface to be implemented by components that want to initialize resources on creation
See Initializer
type IntectorFn ¶ added in v0.0.7
func InjectorOf ¶ added in v0.0.7
func InjectorOf(structType reflect.Type) IntectorFn
type Parameter ¶
type Parameter struct {
// contains filtered or unexported fields
}
Parameter representação de um parametro usado na injeção de dependencias
func (*Parameter) Candidates ¶
Candidates list alternative matches (Ex. value = A, B implements A, B is candidate, if A is missing)
func (*Parameter) HasCandidates ¶
HasCandidates checks if there is any candidate for this parameter
func (*Parameter) IsValidCandidate ¶
func (*Parameter) Provider ¶
Provider indicates that this parameter is a provider (Ex. func(sq Provider[*testService])
func (*Parameter) Qualified ¶
Qualified indicates that this parameter is qualified (Ex. func(sq Qualified[*MyService, MyQualifier])
type PrimaryQualifier ¶
type PrimaryQualifier uint8
type Provider ¶
Provider provides instances of T. For any type T that can be injected, you can also inject Provider<T>. Compared to injecting T directly, injecting Provider<T> enables:
- lazy or optional retrieval of an instance.
- breaking circular dependencies.
Example:
di.Register(func(sp di.Provider[testService]) { if condition { service, err := sp.Get() } })
See Unmanaged
type Qualified ¶
Qualified allows you to inject a dependency that has a qualifier
Example:
type MyQualifier string di.Register(func(sq Qualified[*MyService, MyQualifier]) { myService := sq.Get() })
type ScopeI ¶
type ScopeI interface { // Get return the object with the given Factory from the underlying scope, // creating it if not found in the underlying storage mechanism. // // If CreateObjectFunc returns a disposer, the scope need to register a callback to // be executed on destruction of the specified object in the scope (or at // destruction of the entire scope, if the scope does not destroy individual // objects but rather only terminates in its entirety). Get(context.Context, *Factory, CreateObjectFunc) (any, error) // Remove the object with the given Factory from the underlying scope. // Returns nil if no object was found; otherwise returns the removed Object. Remove(*Factory, any) (any, error) Destroy() }
type Unmanaged ¶
Unmanaged Provider allow the creation of unmanaged instances. The container will not keep track of these instances and the application will be responsible for cleaning them up.
Example:
di.Register(func(up di.Unmanaged[*Seat]) { driver, err := sp.Get() passenger, err := sp.Get() })
See Provider
func (Unmanaged[T]) Get ¶
func (u Unmanaged[T]) Get() (o T, a DisposableAdapter, e error)
Get the value