SkillAgentSearch skills...

Di

Dependency injection container in go (golang)

Install / Use

/learn @sarulabs/Di
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

<p align="center"> <img src="https://raw.githubusercontent.com/sarulabs/assets/master/di/logo_2025.png" width="230" /> </p>

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 
View on GitHub
GitHub Stars712
CategoryDevelopment
Updated13d ago
Forks58

Languages

Go

Security Score

100/100

Audited on Mar 18, 2026

No findings