godi

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2020 License: MIT Imports: 5 Imported by: 7

README

Godi PkgGoDev

Simple Golang DI container based on reflection

Examples: examples folder

Full example: noartem/godi-example

Godoc: pkg.go.dev

Get started

  1. Install godi go get github.com/noartem/godi

  2. Create interfaces and beans implementing these interfaces:

    type IName interface {
        NewName() string
    }
    
    type Name struct {}
    
    func (name *Name) Generate() string {
        return "Lorem Ipsumovich"
    }
    
  3. Create bean factory:

    func NewName() IName {
        return &Name{ ... }
    }
    

    In factory, you can import other beans:

    func NewName(db IDatabase, log ILogger, ...) IName {
        return &Name{
            db: db,
            log: log,
        }
    }
    

    Factories can also return BeanOptions and/or errors:

    func NewName() (IName, *godi.BeanOptions, error) {
        err := someFunc()
        if err != nil {
            return &Name{}, nil, err
        }
    
        options := &godi.BeanOptions{
            Type: godi.Singleton, // Default: godi.Prototype
        }
    
        name := &Name{}
    
        return name, options, nil
    }
    

    or func NewName() (IName, error) {}, or func NewName() (IName, *godi.BeanOptions)

  4. Create DI container and register factories:

    func main() {
        c, err := godi.NewContainer(NewName, NewRandom, NewFoo, ...)
        if err != nil {
            panic(err)
        }
    
        ...
    
  5. Get bean from a container:

        // get bean by interface name
        nameBean, err := c.Get("IName")
        if err != nil {
            panic(err)
        }
    
        name, ok := nameBean.(IName)
        if !ok {
            panic("Invalid name bean")
        }
    
        // now you can use IName
        fmt.Println(name.Generate())
    }
    
  6. Build your architecture based on IOC with DI

  7. Profit! See another examples in examples folder

Other features

  1. Static beans. Can be used for sharing constants (global config, secrets, e.t.c.)

    1. Create a custom type

      type IPassword string
      
    2. Create implementations

      var defaultPassword IPassword = "qwerty123"
      
    3. Register

      godi.NewContainer(defaultPassword)
      

      Constant will be registered as IPassword

    4. Use it

      func NewName(password IPassword) IName {...}
      
  2. Structures with dependencies in Input. If you don't want to write boilerplate code creating structure with all input dependency, you can write them in structure with InStruct field and require this as input in factory.

    1. Create structure based on godi.InStruct and add your dependencies:

      import "github.com/noartem/godi"
      
      type deps struct {
         godi.InStruct
      
         Name IName
         Config IConfig
         Random IRandom
      }
      
    2. Require this structure in factory:

      func NewHello(deps deps) IHello { ... }
      
    3. Use your dependencies:

      func NewHello(deps deps) IHello {
         log.Println(deps.Name.GenerateName())
         log.Println(deps.Config)
         log.Println(deps.Random.Intn(1337))
      }
      

Documentation

Index

Constants

This section is empty.

Variables

View Source
var BeanOptionsType = reflect.TypeOf(&BeanOptions{})

BeanOptionsType reflect type of BeanOptions

View Source
var ErrorInterface = reflect.TypeOf((*error)(nil)).Elem()

ErrorInterface interface of error

View Source
var InStructType = reflect.TypeOf(InStruct{})

InStructType reflect type of BeanOptions

Functions

This section is empty.

Types

type BeanOptions

type BeanOptions struct {
	Type BeanType
}

BeanOptions factory options

type BeanType

type BeanType int

BeanType type of bean

const (
	// Prototype a new instance every time bean is requested
	Prototype BeanType = iota

	// Singleton only one instance of bean per Container
	Singleton
)

type Container

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

Container simple DI container

func NewContainer

func NewContainer(factories ...interface{}) (*Container, error)

NewContainer create new DI container and register dependencies

func NewContainerWithLogger

func NewContainerWithLogger(logger *log.Logger, factories ...interface{}) (*Container, error)

NewContainerWithLogger create new DI container with custom logger and register dependencies

func NewContainerWithLogging added in v0.0.2

func NewContainerWithLogging(factories ...interface{}) (*Container, error)

NewContainerWithLogging create new DI container with default logger

func (*Container) Get

func (container *Container) Get(name string) (interface{}, error)

Get return bean from last registered by name (interface name) factory

func (*Container) GetAll

func (container *Container) GetAll(name string) ([]interface{}, error)

GetAll return beans from all registered by name (interface name) factories

func (*Container) Register

func (container *Container) Register(factories ...interface{}) error

Register add beans factories to DI container

func (*Container) RegisterCompose

func (container *Container) RegisterCompose(registrars ...Registrar) error

RegisterCompose run all registrars

func (*Container) RegisterOne

func (container *Container) RegisterOne(factory interface{}) error

RegisterOne add bean factory to DI container

type InStruct added in v0.0.2

type InStruct struct{}

type Registrar

type Registrar func(c *Container) error

Registrar function registering factories

Directories

Path Synopsis
examples
01_base command
02_http command

Jump to

Keyboard shortcuts

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