Skip to content
/ di Public

Lightweight dependency injection container implements by Go

License

Notifications You must be signed in to change notification settings

gookit/di

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

DI

GoDoc Build Status Coverage Status Go Report Card

中文说明

Lightweight dependency injection container implements by Go.

GoDoc

Install

go get github.com/gookit/di

Usage

package main

import (
    "github.com/gookit/di"
)

func main() {
    box := di.New("my-services")
    
    // add a simple value
    box.Set("service1", "val1")
    
    // register a callback func.
    box.Set("service2", func() (interface, error) {
    	return &MyApp{}, nil
    })
    
    // register a factory func.
    box.Set("service3", func() (interface, error) {
    	return &MyObject{}, nil
    }, true)
    
    // get 
    v1 := box.Get("service1") // "val1"
    
    // is a singleton value. Notice: v2 == v3
    v2 := box.Get("service2").(*MyApp)
    v3 := box.Get("service2").(*MyApp)
    
    // is factory func. Notice: v4 != v5
    v4 := box.Get("service3").(*MyObject)
    v5 := box.Get("service3").(*MyObject)
}

API Methods

  • func (c *Container) Set(name string, val interface{}, isFactory ...bool) *Container
  • func (c *Container) Get(name string) interface{}
  • func (c *Container) SafeGet(name string) (val interface{}, err error)
  • func (c *Container) Inject(ptr interface{}) (err error)

Refer

License

MIT

About

Lightweight dependency injection container implements by Go

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages