The dependence that wrote a Golang notes put in storage, had written last year actually, just be disinclined to write documentation all the time, there just is time recently, combed API interface afresh below, wrote a documentation next, everybody will hold in both hands sing the praises!

Infuse library is depended on Container is development of a language that it is Go when moving. It is not quite easy that the language character of Go language decided those who achieve security of a type to depend on infuse container, because this Container used the reflection mechanism of Go in great quantities. If your use setting is right,performance demand is not that slashing, that Container suits you very much.

Not be to say to asked to cannot be used in harsh environment to function, you are OKContainer Depend on administrative tool as an object, dependent boy or girl friend is gotten when your business initialization.

Use means

go get

Want to foundContainer Example, usecontainier.New Method

cc := container.New()

Founded an empty vessel right now.

You also can be usedcontainer.NewWithContext(ctx) Will found container, after founding, OK and automatic what had existedcontext.Context The object is added in container, by container mandatory.

The object is bound calm

Before use, we need to want us mandatory target to tell recipient first. Container Support the target government of 3 kinds of types

  • Single instance objectSingleton
  • Archetypal object (much exemple object)Prototype
  • String value object is bound calmValue

All objects bind calm method to be able to returnerror Return of value will explain to whether bind calm success, application must check this actively when useerror.

Affirmatory object can bind calm success certainly (the parameter autograph means of the description in disobeying documentation commonly, be regular meeting success) perhaps ask the object must want to bind calm success (normally we ask such, how to undertake dependent administrative otherwise) , can useMust Series method, for instanceSingleton Of methodological correspondence whenMustSingleton, should found when making mistake, this method will be directpanic.

When binding calm object, Singleton, Prototype, BindValue Method to same kind, can bind only decide, if bind those who decide same kind object to found function for many times, can returnErrRepeatedBind Wrong.

Occasionally, hope object founds function to be able to be bound afresh for many times calm, such OK apply more expansibility, can replace an object at any time establish a method, when checking for instanceMock The infuse of the object. At that time we can be usedOverride Series method:

  • SingletonOverride
  • PrototypeOverride
  • BindValueOverride

UseOverride When series method, must assure to be bound for the first time time those who use isOverride Series method, cannot bind afresh otherwise calm.

That is to say, can bind so calmSingletonOverride ->SingletonOverride , SingletonOverride ->Singleton, but once appearSingleton, sequel cannot be bound afresh to this object decided.

Single instance object

UseSingleton The method of series comes target of will single instance is mandatory to container, Single instance object can be finished automatically when be used for the first time only found, later all visits to this object are met the object infuse that will founded automatically comes in.

Commonly used method isSingleton(initialize interface{}) error Method, this method meets what offer according to youinitialize Function or the enrollment that the object will come to achieve single instance target.

Parameterinitialize Support the following kinds of forms:

  • The object founds functionfunc(deps...) Dui Xiang Fan Hui Zhi

    For instance

      cc.Singleton(func() UserRepo { return &userRepoImpl{} })
      cc.Singleton(func() (*sql.DB, error) {
          return sql.Open(\"mysql\", \"user:[email protected](ip:3306)/dbname\")
      cc.Singleton(func(db *sql.DB) UserRepo { 
          //  Zhe  Li  Wo  Men  Chuang  Jian  De  userRepoImpl  Dui  Xiang , Yi  Lai  sql.DB  Dui  Xiang , Zhi  Xu  Yao  Zai  Han  Shu 
          //  Can  Shu  Zhong , Jiang  Yi  Lai  Lie  Ju  Chu  Lai , Rong  Qi  Hui  Zi  Dong  Wan  Cheng  Zhe  Xie  Dui  Xiang  De  Chuang  Jian 
          return &userRepoImpl{db: db} 
  • The boy or girl friend that brings wrong return of value founds functionfunc(deps...) ( Dui Xiang Fan Hui Zhi , error)

    The object founds function to support two return of value at most, and the object that asks by a definite date of the first return of value hopes to found, the 2nd return of value is Error object.

      cc.Singleton(func() (Config, error) {
          //  Jia  She  Wo  Men  Yao  Chuang  Jian  Pei  Zhi  Dui  Xiang , Gai  Dui  Xiang  De  Chu  Shi  Hua  Shi  Cong  Wen  Jian  Du  Qu  Pei  Zhi 
          content, err := ioutil.ReadFile(\"test.conf\")
          if err != nil {
              return nil, err
          return config.Load(content), nil
  • Bind calm object directly

    If the object has been founded, want to letContainer Will manage, can pass the boy or girl friend directlySingleton Method

      userRepo := repo.NewUserRepo()

When target first time is used, Container The executive result cache that can establish the target function rises, the visit after realizing any moment thereby is those who get is same an object.

Archetypal object (much exemple object)

Archetypal object (much exemple object) be point to byContainer Of mandatory target establish a procedure, but using those who depend on infuse to be gotten every time is new the target that establish.

UsePrototype The method of series comes of will archetypal object found mandatory to container. Commonly used method isPrototype(initialize interface{}) error.

Parameterinitialize The type that can accept andSingleton Series function agrees completely, exclusive distinction is when the object is used, single instance object is every time those who return is same an object, and archetypal object is return every time new the target that establish.

String value object is bound calm

This kind ties calm kind is bind a certain object arrive surelyContainer In, but withSingleton What series method differs is, it asks that it must specify type of a stringKey, when getting a boy or girl friend every time, useGet Series function is gotten when binding decided object, deliver this string Key directly can.

Bind calm method commonly usedly to beBindValue(key string, value interface{}).

cc.BindValue(\"version\", \"1.0.1\")
cc.MustBindValue(\"startTs\", time.Now())
cc.BindValue(\"int_val\", 123)

Depend on infuse

Using when binding calm object, normally we are usedResolve AndCall Series method.


Resolve(callback interface{}) error Callback interior can have methodological executive system only depend on infuse, do not receive the return of value of infuse function, although haveerror Return of value, but this value makes clear only whether to produce a mistake when infuse object.

For instance, we need to get the information of a certain user and its part information, use Resolve method

cc.MustResolve(func(userRepo repo.UserRepo, roleRepo repo.RoleRepo) {
    //  Cha  Xun  id=123  De  Yong  Hu , Cha  Xun  Shi  Bai  Zhi  Jie  panic
    user, err := userRepo.GetUser(123)
    if err != nil {
    //  Cha  Xun  Yong  Hu  Jiao  Se , Cha  Xun  Shi  Bai  Shi , Wo  Men  Hu  Lue  Liao  Fan  Hui  De  Cuo  Wu 
    role, _ := roleRepo.GetRole(user.RoleID)

    // do something you want with user/role

Use directlyResolve The method may be not quite contented our daily demand for service, when because be being carried out,inquiring, always can encounter all sorts oferror, discard directly can produce Bug of a lot of hidden, but we also not apt is usedPanic This kind of violent means will solve.

Container OfferredResolveWithError(callback interface{}) error Method, when using this method, our Callback can accepterror Return of value, the problem appears here.

err := cc.ResolveWithError(func(userRepo repo.UserRepo, roleRepo repo.RoleRepoo) error {
    user, err := userRepo.GetUser(123)
    if err != nil {
        return err

    role, err := roleRepo.GetRole(user.RoleID)
    if err != nil {
        return err

    // do something you want with user/role

    return nil
if err != nil {
    //  Zi  Ding  Yi  Cuo  Wu  Chu  Li 


Call(callback interface{}) ([]interface{}, error) The method is over to be resembled in couples not only depend on infuse, still can returncallback return of value, return of value is array structure.

For instance

results, err := cc.Call(func(userRepo repo.UserRepo) ([]repo.User, error) {
    users, err := userRepo.AllUsers()
    return users, err
if err != nil {
    //  Zhe  Li  De  err  Shi  Yi  Lai  Zhu  Ru  Guo  Cheng  Zhong  De  Cuo  Wu , Bi  Ru  Yi  Lai  Dui  Xiang  Chuang  Jian  Shi  Bai 

// results  Shi  Yi  Ge  Lei  Xing  Wei  []interface{}  De  Shu  Zu , Shu  Zu  Zhong  An  Ci  Xu  Bao  Han  Liao  callback  Han  Shu  De  Fan  Hui  Zhi 
// results[0] - []repo.User
// results[1] - error
//  You  Yu  Mei  Ge  Fan  Hui  Zhi  Du  Shi  interface{}  Lei  Xing , Yin  Ci  Zai  Shi  Yong  Shi  Xu  Yao  Zhi  Xing  Lei  Xing  Duan  Yan , Jiang  Qi  Zhuan  Huan  Wei  Ju  Ti  De  Lei  Xing  Zai  Shi  Yong 
users := results[0].([]repo.User)
err := results[0].(error)


Sometimes our hope binds the object implementation that differs surely for different functional module, it is for instance in Web server, the Handler function of every request needs visit and the Request/response boy or girl friend that this second request concerns, after the request ends, Container Medium Request/response object also was not used, requesting those who get differently also is not same an object. We can be usedCallWithProvider(callback interface{}, provider func() []*Entity) ([]interface{}, error) CooperateProvider(initializes ...interface{}) (func() []*Entity, error) The method realizes this function.

ctxFunc := func() Context { return ctx }
requestFunc := func() Request { return ctx.request }

provider, _ := cc.Provider(ctxFunc, requestFunc)
results, err := cc.CallWithProvider(func(userRepo repo.UserRepo, req Request) ([]repo.User, error) {
    //  Zhe  Li  Wo  Men  Zhu  Ru  De  Request  Dui  Xiang , Zhi  Dui  Dang  Qian  callback  You  Xiao 
    userId := req.Input(\"user_id\")
    users, err := userRepo.GetUser(userId)
    return users, err
}, provider)

Infuse of attribute of AutoWire structure style

UseAutoWire Its bind the attribute infuse that the method can be structural style decided object, want to use this character, the structural system that we need to depend on infuse in need is added on the objectautowire Label.

type UserManager struct {
    UserRepo *UserRepo `autowire:\"@\" json:\"-\"`
    field1   string    `autowire:\"version\"`
    Field2   string    `json:\"field2\"`

manager := UserManager{}
//  Dui  manager  Zhi  Xing  AutoWire  Zhi  Hou , Hui  Zi  Dong  Zhu  Ru  UserRepo  He  field1  De  Zhi 
if err := c.AutoWire(&manager); err != nil {
    t.Error(\"test failed\")

Support of infuse of structural style attribute is made public and demesne the infuse of the field. If the object is,come through the type of infuse, useautowire:\"@\" Will label attribute; If use, isBindValue Bind decided string to be the object of Key, useautowire:\"Key Ming Cheng \" Will label attribute.

As a result ofAutoWire Want to revise a target, because this must use the index of the object, structural style type must be used& .

Other method


Methodological autograph

HasBound(key interface{}) bool
HasBoundValue(key string) bool

Whether had bound with the Key that appoints at judgement had been decided.


Methodological autograph

Keys() []interface{}

Get all binding to arrive surelyContainer Medium target information.


Methodological autograph

CanOverride(key interface{}) (bool, error)

Whether can be the Key that judgement appoints enclothed, bind afresh found function surely.


Extend Not beContainer A method on example, however an independent function, use at from already some Container generate a new Container, new Container accedes to already all Container objects are bound calm.

Extend(c Container) Container

After container accedes, when depending on infuse object to search, the meeting is first search from inside current Container, when cannot find a target, search from father object again.

In Container example last, have the name isExtendFrom(parent Container) method, this method is used at appointing current Container to accede from Parent.

Project of give typical examples

Simple give typical examples can consult the Example catalog of the project.

Used in the following projectContainer As depend on infuse management library, those who be interested is OK and referenced.

  • Glacier uses administrative frame, had not written use documentation at present, this frame is compositiveContainer, change with the object example that will manage frame.
  • Adanos-Alert calls the police of use Glacier development system, its side key is not monitoring, call the police however, can be opposite all sorts of calling the police information has group, according to configuration regulation comes to those who realize diversification call the police, use at cooperating commonlyLogstash Those who will achieve business and wrong daily record call the police, cooperatePrometheus, OpenFalcon Wait for mainstream monitoring frame to finish those who serve class to call the police. In still be being developed at present, but basic function is already usable.
  • Development of Sync use Glacier crosses tool of synchronism of lead plane file, have friendly Web to configure an interface, use GRPC realizes different server between the synchronism of the file.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *