di

di

Go语言高性能依赖注入框架

DI是一款专注性能的Go语言依赖注入框架,可高效管理应用中对象的生命周期。该框架支持灵活的对象定义、多种检索方式和作用域管理,有效处理复杂依赖关系。DI适用于各类Go程序,尤其适合管理大量对象和依赖的Web应用。它能在需要时创建对象、解析依赖,并在不再使用时妥善关闭,提升开发效率和程序性能。

依赖注入Go语言ContainerBuilderDefinitionGithub开源项目

DI

Dependency injection framework for go programs (golang).

DI handles the life cycle of the objects in your application. It creates them when they are needed, resolves their dependencies, and closes them properly when they are no longer used.

If you do not know if DI could help improve your application, learn more about dependency injection and dependency injection containers:

There is also an Examples section at the end of the documentation.

DI is focused on performance.

Table of contents

go.dev reference Go version GitHub Workflow Status Coverage

Basic usage

A definition contains at least a Build function to create the object.

MyObjectDef := &di.Def{ Build: func(ctn di.Container) (interface{}, error) { return &MyObject{}, nil }, } // It is possible to add a name or a type to make the definition easier to retrieve. // But it is not mandatory. Check the "Definitions" part of the documentation to learn more about that. MyObjectDef.SetName("my-object") MyObjectDef.SetIs((*MyObject)(nil))

The definition can be added to a builder with the Add method:

builder, err := di.NewEnhancedBuilder() err = builder.Add(MyObjectDef)

Once all the definitions are added to the Builder, you can call the Build method to generate a Container.

ctn, err := builder.Build()

Objects can then be retrieved from the container:

// Either with the definition (recommended) ctn.Get(MyObjectDef).(*MyObject) // Or the name (which is slower) ctn.Get("my-object").(*MyObject) // Or the type (even slower) ctn.Get(reflect.typeOf((*MyObject)(nil))).(*MyObject)

The Get method returns an interface{}. You need to cast the interface before using the object.

The container will only call the definition Build function the first time the Get method is called. After that, the same object is returned (unless the definition has its Unshared field set to true). That means the three calls in the example above return the same pointer. Check the Definitions section to learn more about them.

Builder

EnhancedBuilder usage

You need a builder to create a container.

You should use the EnhancedBuilder. It was introduced to add features that could not be added to the original Builder without breaking backward compatibility.

You need to use the NewEnhancedBuilder function to create the builder. Then you register the definitions with the Add method.

If you add two definitions with the same name, the first one is replaced.

builder, err := di.NewEnhancedBuilder() // Adding a definition named "my-object". err = builder.Add(&di.Def{ Name: "my-object", Build: func(ctn di.Container) (interface{}, error) { return &MyObject{Value: "A"}, nil }, }) // Replacing the definition named "my-object". err = builder.Add(&di.Def{ Name: "my-object", Build: func(ctn di.Container) (interface{}, error) { return &MyObject{Value: "B"}, nil }, }) ctn, err := builder.Build() ctn.Get("my-object").(*MyObject).Value // B

Be sure to handle the errors properly even if it is not the case in this example for conciseness.

EnhancedBuilder limitations

It is only possible to call the EnhancedBuilder.Build function once. After that, it will return an error.

Also, it is not possible to use the same definition in two different EnhancedBuilder.

And you should not update a definition once it has been added to the builder.

All these restrictions exist because the EnhancedBuilder.Build function alters the definitions. It resets the definition fields to their value at the time when the definition was added to the builder. Thus the definitions are linked to the builder and to the container it generates.

Definitions

Definition Build function

A definition only requires a Build function. It is used to create the object.

// You can either use the structure directly. &di.Def{ Build: func(ctn di.Container) (interface{}, error) { return &MyObject{}, nil }, } // Or use the NewDef function to create the definition. di.NewDef(func(ctn di.Container) (interface{}, error) { return &MyObject{}, nil })

The Build function returns the object and an error if it can not be created.

panics in Build functions are recovered and work as if an error was returned.

Definition dependencies

The Build function can also use the container. This allows you to build objects that depend on other objects defined in the container.

MyObjectDef := di.NewDef(func(ctn di.Container) (interface{}, error) { return &MyObject{}, nil }) MyObjectWithDependencyDef := di.NewDef(func(ctn di.Container) (interface{}, error) { // Using the Get method inside the build function is safe. // Panics in this function are recovered. // But be sure to add a name to the definitions if you want understandable error messages. return &MyObjectWithDependency{ Object: ctn.Get(MyObjectDef).(*MyObject), }, nil })

You can not create a cycle in the definitions (A needs B and B needs A). If that happens, an error will be returned at the time of the creation of the object.

Definition name

You can add a name to the definition. It allows you to retrieve the definition from its name.

// Create a definition with a name. MyObjectDef := &di.Def{ Name: "my-object", Build: func(ctn di.Container) (interface{}, error) { return &MyObject{}, nil }, } // The SetName method can also be used. MyObjectDef.SetName("my-object") // Retrieve the definition from the container. ctn.Get("my-object").(*MyObject)

If you do not provide a name, a name will be automatically generated when the container is created.

:warning: Names are used in error messages. So it is recommended to set your own names to avoid troubles when debugging.

Retrieving an object from its name instead of its definition requires an additional lookup in a map[string]int. That makes it significantly slower. If performance is critical for you, you should retrieve objects from their definitions.

Another advantage of using the definitions for object retrieval is that it avoids the risk of a typo in the name.

The drawback is that you need to import the package containing the definitions which may lead to import cycles depending on your project structure.

Definition for an already built object

There is a shortcut to create a definition for an object that is already built.

MyObjectDef = di.NewDefFor(myObject) // is the same as MyObjectDef = &di.Def{ Build: func(ctn di.Container) (interface{}, error) { return myObject, nil }, }

Unshared definitions

By default, the Get method called on the same container always returns the same object. The object is created when the Get method is called for the first time. It is then stored inside the container and the same instance is returned in the next calls. That means that the Build function is only called once.

If you want to retrieve a new instance of the object each time the Get method is called, you need to set the Unshared field of the definition to true.

MyObjectDef = &di.Def{ Unshared: true, // The Build function will be called each time. Build: func(ctn di.Container) (interface{}, error) { return &MyObject{}, nil }, } // ... // o1 != o2 because of Unshared=true o1 := ctn.Get(MyObjectDef).(*MyObject) o2 := ctn.Get(MyObjectDef).(*MyObject)

Definition Close function

A definition can also have a Close function.

di.Def{ Build: func(ctn di.Container) (interface{}, error) { return &MyObject{}, nil }, Close: func(obj interface{}) error { // Assuming that MyObject has a Close method that returns an error on failure. return obj.(*MyObject).Close() }, }

This function is called when the container is deleted.

The deletion of the container must be triggered manually by calling the Delete method.

// Create the Container. app, err := builder.Build() // Retrieve an object. obj := app.Get("my-object").(*MyObject) // Delete the Container, the Close function will be called on obj. err = app.Delete()

Definition types

It is possible to set the type of the object generated by the Build function.

It is only declarative and no checks are done to ensure that this information is valid.

It can be used to retrieve an object by its type instead of its name.

You can set multiple types, for example, a structure and an interface implemented by this structure.

MyObjectDef = di.NewDefFor(myObject) // Declare that myObject is an instance of *MyObject and implements MyInterface. MyObjectDef.SetIs((*MyObject)(nil), (MyInterface)(nil)) // ... // Retrieve the object from the types. ctn.Get(reflect.TypeOf((*MyObject)(nil))).(*MyObject) ctn.Get(reflect.TypeOf((MyInterface)(nil))).(MyInterface)

:warning: If multiple definitions have the same type, the one that was added last in the builder is used to retrieve the object.

It is possible to use the NewBuildFuncForType function to generate a Build function for a given structure (or pointer to a structure). When the object is created using reflection, it will try to set the fields based on their types and the other definitions. There is also a shortcut NewDefForType to create a definition based on NewBuildFuncForType.

// Definition for an already built object, declared having the type *MyObject. MyObjectDef = di.NewDefFor(myObject).SetIs((*MyObject)(nil)) // The definition can create a *MyObjectWithDependency // and the MyObjectWithDependency.Object field will be filled with an object // from the container if there is one with the same type. // NewDefForType does not set the type of the definition. You need to call SetIs yourself if you want to. MyObjectWithDependencyDef := di.NewDefForType((*MyObjectWithDependency)(nil)) // ... // o1 == o2 o1 := ctn.Get(MyObjectWithDependencyDef).(*MyObjectWithDependency).Object o2 := ctn.Get(MyObjectDef).(*MyObject)

:warning: It is not recommended to use this because it is hard to know which fields are set and how. In addition to that, the use of reflection in the generated Build function makes it very slow. The behavior of the NewBuildFuncForType may also change in the future if ways to improve the feature are found.

Definition tags

You can add tags to a definition. Tags are not used internally by this library. They are only there to help you organize your definitions.

MyObjectDef = di.NewDefFor(myObject) tag := di.Tag{ Name: "my-tag", Args: map[string]string{ "tag-argument": "argument-value", }, Data: "Data is an interface{} if Args are not enough", } MyObjectDef.SetTags(tag) MyObjectDef.Tags[0] == tag // true

Object retrieval

When a container is asked to retrieve an object, it starts by checking if the object has already been created. If it has, the container returns the already-built instance of the object. Otherwise, it uses the Build function of the associated definition to create the object. It returns the object, but also keeps a reference to be able to return the same instance if the object is requested again (unless the definition is UnShared).

A container can only build objects defined in the same scope (scopes documentation). If the container is asked to retrieve an object that belongs to a different scope. It forwards the request to its parent.

There are three methods to retrieve an object: Get, SafeGet and Fill.

Get

Get returns an interface that can be cast afterward. If the object can not be created, the Get function panics.

// Retrieve the object from the definition (recommended) o1 := ctn.Get(MyObjectDef).(*MyObject) // Or from its name (which is slower) o2 := ctn.Get("my-object").(*MyObject) // Or from its type (even slower) o3 := ctn.Get(reflect.typeOf((*MyObject)(nil))).(*MyObject) // o1 == o2 == o3

SafeGet

Get is an easy way to retrieve an object. The problem is that it can panic. If it is a problem for you, you can use SafeGet. Instead of panicking, it returns an error.

objectInterface, err := ctn.SafeGet(MyObjectDef) // You still need to cast the interface. object, ok := objectInterface.(*MyObject) // SafeGet can also be called with a definition name or type. objectInterface, err = ctn.SafeGet("my-object") objectInterface, err = ctn.SafeGet(reflect.typeOf((*MyObject)(nil)))

Fill

The third method to retrieve an object is Fill. It returns an error if something goes wrong like SafeGet, but it may be more practical in some situations. It uses reflection to fill the given object. Using reflection makes it slower than SafeGet.

var object *MyObject err := ctn.Fill(MyObjectDef, &object) // Fill can also be called with a definition name or type. err = ctn.Fill("my-object", &object) err = ctn.Fill(reflect.typeOf((*MyObject)(nil)), &object)

Scopes

The principle

Definitions can also have a scope. They can be useful in request-based applications, such as a web application.

MyObjectDef := &di.Def{ Scope: di.Request, Build: func(ctn di.Container) (interface{}, error) { return &MyObject{}, nil }, }

The available scopes are defined when the Builder is created:

builder, err := di.NewEnhancedBuilder(di.App, di.Request)

Scopes are defined from the most generic to the most specific (eg: AppRequestSubRequest). If no scope is given to NewEnhancedBuilder, the builder is created with the three default scopes: di.App, di.Request and di.SubRequest. These scopes should be enough almost all the time.

The containers belong to one of these scopes. A container may have a parent in a more generic scope and children in a more specific scope. The builder generates a container in the most generic scope. Then the container can generate children in the next scope thanks to the SubContainer method.

A container is only able to build objects defined in its own scope, but it can retrieve objects in a more generic scope thanks to its parent. For example, a Request container can retrieve an App object, but an App container can not retrieve a Request object.

If a definition does not have a scope, the most generic scope will be used.

Scopes in practice

// Create a Builder with the default scopes (App, Request, SubRequest). builder, err := di.NewEnhancedBuilder() // Define an object in the App scope. AppDef := di.Def{ Scope: di.App, // this line is optional, di.App is the default scope Build: func(ctn di.Container) (interface{}, error) { return &MyObject{}, nil }, } err =

编辑推荐精选

Refly.AI

Refly.AI

最适合小白的AI自动化工作流平台

无需编码,轻松生成可复用、可变现的AI自动化工作流

酷表ChatExcel

酷表ChatExcel

大模型驱动的Excel数据处理工具

基于大模型交互的表格处理系统,允许用户通过对话方式完成数据整理和可视化分析。系统采用机器学习算法解析用户指令,自动执行排序、公式计算和数据透视等操作,支持多种文件格式导入导出。数据处理响应速度保持在0.8秒以内,支持超过100万行数据的即时分析。

AI工具酷表ChatExcelAI智能客服AI营销产品使用教程
TRAE编程

TRAE编程

AI辅助编程,代码自动修复

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
AIWritePaper论文写作

AIWritePaper论文写作

AI论文写作指导平台

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

AI辅助写作AI工具AI论文工具论文写作智能生成大纲数据安全AI助手热门
博思AIPPT

博思AIPPT

AI一键生成PPT,就用博思AIPPT!

博思AIPPT,新一代的AI生成PPT平台,支持智能生成PPT、AI美化PPT、文本&链接生成PPT、导入Word/PDF/Markdown文档生成PPT等,内置海量精美PPT模板,涵盖商务、教育、科技等不同风格,同时针对每个页面提供多种版式,一键自适应切换,完美适配各种办公场景。

AI办公办公工具AI工具博思AIPPTAI生成PPT智能排版海量精品模板AI创作热门
潮际好麦

潮际好麦

AI赋能电商视觉革命,一站式智能商拍平台

潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。

iTerms

iTerms

企业专属的AI法律顾问

iTerms是法大大集团旗下法律子品牌,基于最先进的大语言模型(LLM)、专业的法律知识库和强大的智能体架构,帮助企业扫清合规障碍,筑牢风控防线,成为您企业专属的AI法律顾问。

SimilarWeb流量提升

SimilarWeb流量提升

稳定高效的流量提升解决方案,助力品牌曝光

稳定高效的流量提升解决方案,助力品牌曝光

Sora2视频免费生成

Sora2视频免费生成

最新版Sora2模型免费使用,一键生成无水印视频

最新版Sora2模型免费使用,一键生成无水印视频

Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

下拉加载更多