di

package
v0.14.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 27, 2023 License: MIT Imports: 5 Imported by: 0

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

View Source
var (
	ErrCtorNotFunc        = errors.New("ctor is not func")
	ErrWrongCtorSignature = errors.New("ctor must return only service value")
)
View Source
var (
	ErrNotRegistered    = errors.New("dependency is not registered")
	ErrCyclicDependency = errors.New("cyclic dependency detected")
	ErrNotAddresable    = errors.New("need to pass address")
	ErrNotPointer       = errors.New("must be a pointer")
)

Functions

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.

type Constructor added in v0.8.0

type Constructor interface {
	// Create returns created instance from called ctor with parameters retrieved with provider.
	Create(provider func(reflect.Type) interface{}) interface{}

	// Type returns a reflect.Type for object that can be created by this constructor.
	Type() reflect.Type

	// Dependencies returns an array of reflect.Type defining type of dependencies for object to construct.
	Dependencies() []reflect.Type

	// Life returns LifeTime which defines scope of existance for constructed object.
	Life() LifeTime
}

Constructor is interface for delegate the Create function which has passed the provider for dependency resolving while instantiating a new instace of concrete type.

func Construct

func Construct(life LifeTime, ctor any) Constructor

Construct returns a new Constructor instance for specified function. It panics if ctor is not a function or it does not return any value.

type ConstructorFunc added in v0.8.0

type ConstructorFunc func(provider func(reflect.Type) interface{}) interface{}

ConstructorFunc is simple func type that implements Constructor.

func (ConstructorFunc) Create added in v0.8.0

func (f ConstructorFunc) Create(provider func(reflect.Type) interface{}) interface{}

type Container

type Container interface {
	// Validate verifies if every dependency is registered to provide services without
	// missing dependency issue and tests if there is no cyclic dependency.
	Validate() error

	// Provide creates service from found constructor and sets the result to v. It will panic
	// if constructor cannot be found or v is not a pointer. Singleton services are cahced in
	// root cache. If container is scoped it will cache also Scoped services. Transient services
	// are always recreated from constructor.
	Provide(v interface{})

	// Scope returns a new scoped container which will cache scoped lifetime services.
	Scope() Container

	// Services returns an array of registered services.
	Services() []Service
}

Container is implemented by any value that has a Validate, Provide and Register method. The implementation controls how constructors are registered or provided inside container and what are requirements must be met to consider container as valid instance.

func Register

func Register(ctors ...any) (c Container, err error)

Register returns a new container instance with constructor services. Construct or func constructor can be passed. Error will be returned if any func constructor is not valid or Validate on container will return error.

type LifeTime

type LifeTime int

LifeTime is value defining scope of life for object.

const (
	Transient LifeTime = iota
	Singleton
	Scoped
)

type Service added in v0.8.0

type Service struct {
	// contains filtered or unexported fields
}

func (Service) Constructor added in v0.8.0

func (s Service) Constructor() Constructor

func (Service) Type added in v0.8.0

func (s Service) Type() reflect.Type

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL