di

package module
v2.5.1 Latest Latest
Warning

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

Go to latest
Published: Jul 13, 2024 License: MIT Imports: 10 Imported by: 106

README

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.

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)

⚠ 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)

⚠ 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 = builder.Add(AppDef)

// Define an object in the Request scope.
RequestDef := di.Def{
    Scope: di.Request,
    Build: func(ctn di.Container) (interface{}, error) {
        return &MyObject{}, nil
    },
}
err = builder.Add(RequestDef)

// Build creates a Container in the most generic scope (App).
app, err := builder.Build()

// The App Container can create sub-containers in the Request scope.
req1, err := app.SubContainer()
req2, err := app.SubContainer()

// app-object can be retrieved from the three containers.
// The retrieved objects are the same: o1 == o2 == o3.
// The object is stored in app.
o1 := app.Get(AppDef).(*MyObject)
o2 := req1.Get(AppDef).(*MyObject)
o3 := req2.Get(AppDef).(*MyObject)

// request-object can only be retrieved from req1 and req2.
// The retrieved objects are not the same: o4 != o5.
// o4 is stored in req1, and o5 is stored in req2.
o4 := req1.Get(RequestDef).(*MyObject)
o5 := req2.Get(RequestDef).(*MyObject)

More graphically, the containers could be represented like this:

The App container can only get the App object. A Request container or a SubRequest container can get either the App object or the Request object, possibly by using their parent. The objects are built and stored in containers that have the same scope. They are only created when they are requested.

Scopes and dependencies

If an object depends on other objects defined in the container, the scopes of the dependencies must be either equal or more generic compared to the object scope.

For example the following definitions are not valid:

di.Def{
    Name: "request-object",
    Scope: di.Request,
    Build: func(ctn di.Container) (interface{}, error) {
        return &MyObject{}, nil
    },
}

di.Def{
    Name: "object-with-dependency",
    Scope: di.App, // NOT ALLOWED !!! should be di.Request or di.SubRequest
    Build: func(ctn di.Container) (interface{}, error) {
        return &ObjectWithDependency{
            Object: ctn.Get("request-object").(*MyObject),
        }, nil
    },
}

Container deletion

When you no longer need a container, you can delete it.

err := ctn.Delete()

Delete closes all the objects stored in the Container by calling their Close function.

Deleting the container makes it unusable, but it frees its memory. So you probably should use it even if none of your definitions have a Close function.

If there are dependencies between definitions, the Close functions are called in the right order (dependencies after).

Deleting containers is very useful when using scopes. You will want to delete the Request container at the end of each request. The App container will still be usable.

There are two delete methods: Delete and DeleteWithSubContainers

DeleteWithSubContainers deletes the children of the Container and then the Container. It does this right away. Delete is a softer approach. It does not delete the children of the Container. Actually it does not delete the Container as long as it still has a child alive. So you have to call Delete on all the children. The parent Container will be deleted when Delete is called on the last child.

You probably want to use Delete and close the children manually. DeleteWithSubContainers can cause errors if the parent is deleted while its children are still used.

Unscoped retrieval

The Get, SafeGet and Fill functions can retrieve an object defined in the same scope or a more generic one. If you need an object defined in a more specific scope, you need to create a sub-container to retrieve it. For example, an App container can not create a Request object. A Request container should be created to retrieve the Request object. It is logical but not always very practical.

UnscopedGet, UnscopedSafeGet and UnscopedFill work like Get, SafeGet and Fill but can retrieve objects defined in a more generic scope. To do so, they generate sub-containers that can only be accessed internally by these three methods. To remove these containers without deleting the current container, you can call the Clean method.

⚠ Do not use unscope functions inside a Build function. In this case, circular definitions are not detected. If you do this, you take the risk of having an infinite loop in your code when building an object.

builder, err := di.NewEnhancedBuilder()

err = builder.Add(di.Def{
    Name: "request-object",
    Scope: di.Request,
    Build: func(ctn di.Container) (interface{}, error) {
        return &MyObject{}, nil
    },
    Close: func(obj interface{}) error {
        return obj.(*MyObject).Close()
    },
})

app, err := builder.Build()

// app can retrieve a request-object with unscoped methods.
obj := app.UnscopedGet("request-object").(*MyObject)

// Once the objects created with unscoped methods are no longer used,  you can call the Clean method.
// In this case, the Close function will be called on the object.
err = app.Clean()

HTTP helpers

DI includes some elements to ease its integration into web applications.

The HTTPMiddleware function can be used to inject a container in an http.Request.

// Create an App container.
builder, err := di.NewEnhancedBuilder()
err = builder.Add(/* some definitions */)
app, err := builder.Build()

handlerWithDiMiddleware := di.HTTPMiddleware(handler, app, func(msg string) {
    logger.Error(msg) // Use your own logger here, it is used to log container deletion errors.
})

For each http.Request, a sub-container of the app container is created. It is deleted at the end of the http request.

The container can be used in the handler:

handler := func(w http.ResponseWriter, r *http.Request) {
    // Retrieve the Request container with the C function.
    ctn := di.C(r)
    obj := ctn.Get("object").(*MyObject)

    // There is also a shortcut to do that.
    obj := di.Get(r, "object").(*MyObject)
}

The handler and the middleware can panic. Do not forget to use another middleware to recover from the panic and log the errors.

Examples

The sarulabs/di-example repository is a good example to understand how DI can be used in a web application.

More explanations about this repository can be found in this blog post:

If you do not have time to check this repository, here is a shorter example that does not use the HTTP helpers. It does not handle the errors to be more concise.

package main

import (
    "context"
    "database/sql"
    "net/http"

    "github.com/sarulabs/di/v2"

    _ "github.com/go-sql-driver/mysql"
)

var MysqlPoolDef = &di.Def{
    // Define the connection pool in the App scope.
    // There will be one for the whole application.
    Name:  "mysql-pool",
    Scope: di.App,
    Build: func(ctn di.Container) (interface{}, error) {
        db, err := sql.Open("mysql", "user:password@/")
        db.SetMaxOpenConns(1)
        return db, err
    },
    Close: func(obj interface{}) error {
        return obj.(*sql.DB).Close()
    },
}

var MySqlDef = &di.Def{
    // Define the connection in the Request scope.
    // Each request will use its own connection.
    Name:  "mysql",
    Scope: di.Request,
    Build: func(ctn di.Container) (interface{}, error) {
        pool := ctn.Get("mysql-pool").(*sql.DB)
        return pool.Conn(context.Background())
    },
    Close: func(obj interface{}) error {
        return obj.(*sql.Conn).Close()
    },
}

func main() {
    builder, _ := di.NewEnhancedBuilder()
    builder.Add(MysqlPoolDef)
    builder.Add(MySqlDef)
    app, _ := builder.Build()
    defer app.Delete()

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        // Create a request and delete it once it has been handled.
        // Deleting the request will close the connection.
        request, _ := app.SubContainer()
        defer request.Delete()

        handler(w, r, request)
    })

    http.ListenAndServe(":8080", nil)
}

func handler(w http.ResponseWriter, r *http.Request, ctn di.Container) {
    // Retrieve the connection.
    conn := ctn.Get(MySqlDef).(*sql.Conn)

    var variable, value string

    row := conn.QueryRowContext(context.Background(), "SHOW STATUS WHERE `variable_name` = 'Threads_connected'")
    row.Scan(&variable, &value)

    // Display how many connections are opened.
    // As the connection is closed when the request is deleted,
    // the value should not be higher than the number set with db.SetMaxOpenConns(1).
    w.Write([]byte(variable + ": " + value))
}

Performance

Retrieving an object from a container will always be slower than directly using a variable. That being said, DI tries to minimize the cost of using containers.

Get parameter

The Get method accepts different types as parameters. If possible you should use a di.Def as it is the fastest.

Even if it is a bit slower (additional lookup in a map[string]int to get the associated di.Def), using the name of the definition is still pretty fast and is an acceptable choice in most applications.

Shared objects

When using shared objects (which is the default with Def.Unshared set to false), the first call to the Get method will create the object. After its creation, it must be stored in the container. This can be relatively slow as to avoid data races it uses a mutex and blocks the container for a brief moment.

It should not be an issue in most applications. But if you need the object retrieval to be really fast, you need to call the Get method before the critical path in your application to preload the container. After that, the next calls to Get will be much faster.

Unshared object

Unshared objects may also be stored in the container if they have a Close function (otherwise they could not closed). So retrieving these objects is slow as it blocks the container with a mutex. So if you are looking to improve the performance of your container, avoid using Unshared definitions with a Close function.

Deep nesting

Definitions with a lot of dependencies at several levels (dependencies having dependencies) are likely to be slow to build compared to creating the object manually.

Documentation

Index

Constants

View Source
const App = "app"

App is the name of the application scope.

View Source
const Request = "request"

Request is the name of the request scope.

View Source
const SubRequest = "subrequest"

SubRequest is the name of the subrequest scope.

Variables

View Source
var C = func(i interface{}) Container {
	if c, ok := i.(Container); ok {
		return c
	}

	r, ok := i.(*http.Request)
	if !ok {
		panic("could not get the container with C()")
	}

	c, ok := r.Context().Value(ContainerKey("di")).(Container)
	if !ok {
		panic("could not get the container from the given *http.Request")
	}

	return c
}

C retrieves a Container from an interface. The function panics if the Container can not be retrieved.

The interface can be :

  • a Container
  • an *http.Request containing a Container in its context.Context for the ContainerKey("di") key.

The function can be changed to match the needs of your application.

Functions

func Get

func Get(i interface{}, name string) interface{}

Get is a shortcut for C(i).Get(name).

func HTTPMiddleware

func HTTPMiddleware(h http.HandlerFunc, app Container, logFunc func(msg string)) http.HandlerFunc

HTTPMiddleware adds a container in the request context.

The container injected in each request, is a new sub-container of the app container given as parameter.

It can panic, so it should be used with another middleware to recover from the panic, and to log the error.

It uses logFunc, a function that can log an error. logFunc is used to log the errors during the container deletion.

func NewBuildFuncForType added in v2.5.0

func NewBuildFuncForType(obj interface{}) (func(ctn Container) (interface{}, error), error)

NewBuildFuncForType returns a Build function that creates an instance of an object having the same type as the given obj. Only structures and pointers to structures are supported as input parameter. It will try to set the fields of the generated struct with objects from the container. Only definitions with a Is field including the type of the field can be used. If there is no definition for the field type, the field is left empty. If there are more than one definition for the field type, the one that was inserted last in the builder is used.

func NewIs added in v2.5.0

func NewIs(instances ...interface{}) []reflect.Type

NewIs applies reflect.TypeOf to all the given instances and returns a slice of []reflect.Type. It can be used to fill the Def.Is field.

Types

type Builder

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

Builder can be used to create a Container. The Builder should be created with NewBuilder. Then you can add definitions with the Add method, and finally build the Container with the Build method.

Consider using the EnhancedBuilder that provides more features.

func NewBuilder

func NewBuilder(scopes ...string) (*Builder, error)

NewBuilder is the only way to create a working Builder. It initializes a Builder with a list of scopes. The scopes are ordered from the most generic to the most specific. If no scope is provided, the default scopes are used: [App, Request, SubRequest] It can return an error if the scopes are not valid.

func (*Builder) Add

func (b *Builder) Add(defs ...Def) error

Add adds one or more definitions in the Builder. It returns an error if a definition can not be added. If a definition with the same name has already been added, it will be replaced by the new one, as if the first one never existed.

func (*Builder) Build

func (b *Builder) Build() Container

Build creates a Container in the most generic scope with all the definitions registered in the Builder.

func (*Builder) Definitions

func (b *Builder) Definitions() DefMap

Definitions returns a map with the all the objects definitions registered with the Add method. The key of the map is the name of the Definition.

func (*Builder) IsDefined

func (b *Builder) IsDefined(name string) bool

IsDefined returns true if there is a definition with the given name.

func (*Builder) Scopes

func (b *Builder) Scopes() ScopeList

Scopes returns the list of available scopes.

func (*Builder) Set added in v2.4.0

func (b *Builder) Set(name string, obj interface{}) error

Set is a shortcut to add a definition for an already built object.

type Container

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

Container represents a dependency injection container. To create a Container, you should use a Builder, an EnhancedBuilder or another Container.

A Container has a scope and may have a parent in a more generic scope and children in a more specific scope. Objects can be retrieved from the Container. If the requested object does not already exist in the Container, it is built thanks to the object definition.

func (Container) Clean

func (ctn Container) Clean() error

Clean deletes the sub-container created by UnscopedSafeGet, UnscopedGet or UnscopedFill.

func (Container) Definitions

func (ctn Container) Definitions() map[string]Def

Definitions returns the map of the available definitions ordered by name. These definitions represent all the objects that this Container can build.

func (Container) DefinitionsForType added in v2.5.0

func (ctn Container) DefinitionsForType(typ reflect.Type) []Def

DefinitionsForType returns the list of the definitions matching the given type. Types are declared in the Is field of a definition.

func (Container) Delete

func (ctn Container) Delete() error

Delete works like DeleteWithSubContainers if the Container does not have any child. But if the Container has sub-containers, it will not be deleted right away. The deletion only occurs when all the sub-containers have been deleted manually. So you have to call Delete or DeleteWithSubContainers on all the sub-containers.

func (Container) DeleteWithSubContainers

func (ctn Container) DeleteWithSubContainers() error

DeleteWithSubContainers takes all the objects saved in this Container and calls the Close function of their Definition on them. It will also call DeleteWithSubContainers on each child and remove its reference in the parent Container. After deletion, the Container can no longer be used. The sub-containers are deleted even if they are still used in other goroutines. It can cause errors. You may want to use the Delete method instead.

func (Container) Fill

func (ctn Container) Fill(in interface{}, dst interface{}) error

Fill is similar to SafeGet but it does not return the object. Instead it fills the provided object with the value returned by SafeGet. The provided object must be a pointer to the value returned by SafeGet. It uses reflection so it is slower than Get and SafeGet. But it can be convenient in some cases where performance is not a critical factor.

func (Container) Get

func (ctn Container) Get(in interface{}) interface{}

Get retrieves an object from the Container. The object has to belong to the Container or one of its parents. If the object does not already exist, it is created and saved in the Container. If the object can not be created, it panics.

There are different ways to retrieve an object.

  • From its name: ctn.Get("object-name")
  • From its definition: ctn.Get(objectDef) or ctn.Get(objectDefPtr) - only with the EnhancedBuilder
  • From its index: ctn.Get(objectDef.Index()) - only with the EnhancedBuilder
  • From its type: ctn.Get(reflect.typeOf(MyObject{})) - only if objectDef.Is includes the given type In case there are more than one definition matching the given type, the chosen one is the last definition inserted in the builder.

func (Container) IsClosed

func (ctn Container) IsClosed() bool

IsClosed returns true if the Container has been deleted.

func (Container) NameIsDefined added in v2.5.0

func (ctn Container) NameIsDefined(name string) bool

NameIsDefined returns true if there is a definition for the given name.

func (Container) Parent

func (ctn Container) Parent() Container

Parent returns the parent Container. It works like ParentContainer but without the error. This method was kept to have some kind of backward compatibility.

func (Container) ParentContainer added in v2.5.1

func (ctn Container) ParentContainer() (Container, error)

ParentContainer returns the parent Container. If the Container does not have a parent, it returns an error.

func (Container) ParentScopes

func (ctn Container) ParentScopes() []string

ParentScopes returns the list of scopes that are more generic than the Container scope.

func (Container) SafeGet

func (ctn Container) SafeGet(in interface{}) (interface{}, error)

SafeGet retrieves an object from the Container. The object has to belong to the Container or one of its parents. If the object does not already exist, it is created and saved in the Container. If the object can not be created, it returns an error.

There are different ways to retrieve an object.

  • From its name: ctn.SafeGet("object-name")
  • From its definition: ctn.SafeGet(objectDef) or ctn.SafeGet(objectDefPtr) - only with the EnhancedBuilder
  • From its index: ctn.SafeGet(objectDef.Index()) - only with the EnhancedBuilder
  • From its type: ctn.SafeGet(reflect.typeOf(MyObject{})) - only if objectDef.Is includes the given type In case there are more than one definition matching the given type, the chosen one is the last definition inserted in the builder.

func (Container) Scope

func (ctn Container) Scope() string

Scope returns the Container scope.

func (Container) Scopes

func (ctn Container) Scopes() []string

Scopes returns the list of available scopes.

func (Container) SubContainer

func (ctn Container) SubContainer() (Container, error)

SubContainer creates a new Container in the next sub-scope that will have this Container as parent.

func (Container) SubScopes

func (ctn Container) SubScopes() []string

SubScopes returns the list of scopes that are more specific than the Container scope.

func (Container) TypeIsDefined added in v2.5.0

func (ctn Container) TypeIsDefined(typ reflect.Type) bool

TypeIsDefined returns true if there is a definition for the given type. Types are declared in the Is field of a definition.

func (Container) UnscopedFill

func (ctn Container) UnscopedFill(in interface{}, dst interface{}) error

UnscopedFill is similar to UnscopedSafeGet but copies the object in dst instead of returning it.

func (Container) UnscopedGet

func (ctn Container) UnscopedGet(in interface{}) interface{}

UnscopedGet is similar to UnscopedSafeGet but it does not return the error. Instead it panics.

func (Container) UnscopedSafeGet

func (ctn Container) UnscopedSafeGet(in interface{}) (interface{}, error)

UnscopedSafeGet retrieves an object from the Container, like SafeGet. The difference is that the object can be retrieved even if it belongs to a more specific scope. To do so, UnscopedSafeGet creates a sub-container. When the created object is no longer needed, it is important to use the Clean method to delete this sub-container.

/!\ Do not use unscope functions inside a `Build` function. In this case, circular definitions are not detected. If you do this, you take the risk of having an infinite loop in your code when building an object.

type ContainerKey

type ContainerKey string

ContainerKey is a type that can be used to store a container in the context.Context of an http.Request. By default, it is used in the C function and the HTTPMiddleware.

type Def

type Def struct {
	// Build is the function that is used to create the object.
	Build func(ctn Container) (interface{}, error)
	// Close is the function that is used to clean the object when the container is deleted.
	// It can be nil if nothing needs to be done to close the object.
	Close func(obj interface{}) error
	// Name is the key that is used to retrieve the object from the container.
	Name string
	// Scope determines in which container the object is stored.
	// Typical scopes are "app" and "request".
	Scope string
	// Unshared is false by default. That means that the object is only created once in a given container.
	// They are singleton and the same instance will be returned each time "Get", "SafeGet" or "Fill" is called.
	// If you want to retrieve a new object every time, "Unshared" needs to be set to true.
	Unshared bool
	// Is allows to declare 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.
	// You can set multiple types, for example a structure and an interface implemented by the structure.
	// The Is field can be used to retrieve an object by its type instead of its name.
	// e.g.: ctn.Get(reflect.Type(MyStruct{}))
	// If multiple definitions have the same type, the one that was added last in the builder is used to retrieve the object.
	// The Is field is important if you are using NewBuildFuncForType.
	// It allows to create a Build function that creates an object whose fields are filled
	// depending on their type and the types of the definitions in the Container.
	Is []reflect.Type
	// Tags are not used inside this library. But they can be useful to sort your definitions.
	Tags []Tag
	// contains filtered or unexported fields
}

Def contains information to build and close an object inside a Container.

func NewDef added in v2.5.0

func NewDef(buildFunc func(ctn Container) (interface{}, error)) *Def

NewDef creates a new *Def with only the Build function field set. You can also use the Def structure directly if it better fits your needs.

func NewDefFor added in v2.5.0

func NewDefFor(obj interface{}) *Def

NewDefFor creates a definition for an already built object. It is meant to replace the Set("object-name", objectInstance) of the basic Builder. If you want to add a name to the definition, you can use the setters. e.g.: NewDefFor(objectInstance).SetName("object-name")

func NewDefForType added in v2.5.0

func NewDefForType(obj interface{}) *Def

NewDefForType creates a definition that uses the result of NewBuildFuncForType(obj) as a Build function. The object generated by this definition will have the same type as the obj parameter. obj can only be a struct or a pointer to a struct. Other types are not supported. The fields of the generated object are filled with objects from the container depending on their types and the Is field of the definitions in the Container.

The object will be generated using reflection. That implies that it is slower compared to a manually written function. But if you just use this for shared definitions in the main scope, it should not be a problem as the objects are only built once.

func (*Def) Index added in v2.5.0

func (d *Def) Index() int

Index returns the index of the definition in its Container. If the definition is not bound to a Container, it returns -1.

func (*Def) SetBuild added in v2.5.0

func (d *Def) SetBuild(build func(ctn Container) (interface{}, error)) *Def

SetBuild is the setter for the Build field.

func (*Def) SetClose added in v2.5.0

func (d *Def) SetClose(close func(obj interface{}) error) *Def

SetClose is the setter for the Close field.

func (*Def) SetIs added in v2.5.0

func (d *Def) SetIs(instances ...interface{}) *Def

SetIs is the setter for the Is field. But the input parameters are not reflect.Type, but object instances. It uses NewIs to convert instances to []reflect.Type.

func (*Def) SetName added in v2.5.0

func (d *Def) SetName(name string) *Def

SetName is the setter for the Name field.

func (*Def) SetScope added in v2.5.0

func (d *Def) SetScope(scope string) *Def

SetScope is the setter for the Scope field.

func (*Def) SetTags added in v2.5.0

func (d *Def) SetTags(tags ...Tag) *Def

SetTags is the setter for the Tag field.

func (*Def) SetUnshared added in v2.5.0

func (d *Def) SetUnshared(unshared bool) *Def

SetUnshared is the setter for the Unshared field.

type DefMap

type DefMap map[string]Def

DefMap is a collection of Def ordered by name.

func (DefMap) Copy

func (m DefMap) Copy() DefMap

Copy returns a copy of the DefMap.

type EnhancedBuilder added in v2.5.0

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

EnhancedBuilder can be used to create a Container. The EnhancedBuilder should be created with NewEnhancedBuilder. Then you can add definitions with the Add method. Once all the definitions have been added to the builder, you can generate the Container with the Build method.

It works the same way as the basic Builder. But the definitions given to the Add method are pointers. The definitions are updated when the Build method is called. That allows to retrieve objects by their definitions which is faster than retrieving them by name.

func NewEnhancedBuilder added in v2.5.0

func NewEnhancedBuilder(scopes ...string) (*EnhancedBuilder, error)

NewEnhancedBuilder is the only way to create a working EnhancedBuilder. It initializes an EnhancedBuilder with a list of scopes. The scopes are ordered from the most generic to the most specific. If no scope is provided, the default scopes are used: [App, Request, SubRequest] It can return an error if the scopes are not valid.

func (*EnhancedBuilder) Add added in v2.5.0

func (b *EnhancedBuilder) Add(def *Def) error

Add adds one definition to the Builder. It returns an error if the definition can not be added.

The name must be unique. If a definition with the same name has already been added, it will be replaced by the new one, as if the first one never was added. If an empty name is provided, a name starting with "_di_generated_" is generated. You can not add a definition with a name starting with "_di_generated_" as it is reserved for auto-genrated ones. Providing a name is recommended as it makes errors much easier to understand.

The input definition is a pointer. It will be updated when the container is generated with the Build method. It binds the definition to the generated Container. That allows to build an object not only from its name but also from its definition which happens to be faster.

func (*EnhancedBuilder) Build added in v2.5.0

func (b *EnhancedBuilder) Build() (Container, error)

Build creates a Container in the most generic scope with all the definitions registered in the builder.

The definition provided in the Add method are updated to match their state when they were added to the builder.

A definition can only belong to one container. That means you can only call Build once.

func (*EnhancedBuilder) Definitions added in v2.5.0

func (b *EnhancedBuilder) Definitions() DefMap

Definitions returns a map with the all objects definitions registered at this point. The key of the map is the name of the definition.

func (*EnhancedBuilder) NameIsDefined added in v2.5.0

func (b *EnhancedBuilder) NameIsDefined(name string) bool

NameIsDefined returns true if there is a definition registered with the given name.

func (*EnhancedBuilder) Scopes added in v2.5.0

func (b *EnhancedBuilder) Scopes() ScopeList

Scopes returns the list of available scopes.

type ScopeList

type ScopeList []string

ScopeList is a slice of scope.

func (ScopeList) Contains

func (l ScopeList) Contains(scope string) bool

Contains returns true if the ScopeList contains the given scope.

func (ScopeList) Copy

func (l ScopeList) Copy() ScopeList

Copy returns a copy of the ScopeList.

func (ScopeList) ParentScopes

func (l ScopeList) ParentScopes(scope string) ScopeList

ParentScopes returns the scopes before the one given as parameter.

func (ScopeList) SubScopes

func (l ScopeList) SubScopes(scope string) ScopeList

SubScopes returns the scopes after the one given as parameter.

type Tag

type Tag struct {
	Name string
	Args map[string]string
	Data interface{}
}

Tag can contain more specific information about a Definition. It is useful to find a Definition thanks to its tags instead of its name.

Jump to

Keyboard shortcuts

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