Skip to main content
DISCLAIMER: This is a beta package. The SDK team is actively working on this feature and we are looking for feedback from the community. Please try it out and let us know what you think.

Overview

depinject is a dependency injection framework for the Cosmos SDK. This module together with core/appconfig are meant to simplify the definition of a blockchain by replacing most of app.go’s boilerplate code with a configuration file (Go, YAML or JSON).

Usage

depinject includes an expressive and composable Configuration API. A core configuration function is Provide. The example below demonstrates the registration of free provider functions via the Provide API.
Provider functions form the basis of the dependency tree, they are introspected then their inputs identified as dependencies and outputs as dependants, either for another provider function or state stored outside the DI container, as is the case of &x and &y above.

Interface type resolution

depinject supports interface types as inputs to provider functions. In the SDK’s case this pattern is used to decouple Keeper dependencies between modules. For example x/bank expects an AccountKeeper interface as input to ProvideModule. Concretely SimApp uses the implementation in x/auth, but this design allows for this loose coupling to change. Given the following types:
This usage
results in an implicit binding of Duck to Mallard. This works because there is only one implementation of Duck in the container.
However, adding a second provider of Duck will result in an error:
A specific binding preference for Duck is required.

BindInterface API

In the above situation registering a binding for a given interface binding may look like
Now depinject has enough information to provide Mallard as an input to APond.

Full example in real app

When using depinject.Inject, the injected types must be pointers.

Debugging

Issues with resolving dependencies in the container can be done with logs and Graphviz renderings of the container tree. By default, whenever there is an error, logs will be printed to stderr and a rendering of the dependency graph in Graphviz DOT format will be saved to debug_container.dot. Here is an example Graphviz rendering of a successful build of a dependency graph: Graphviz Example Rectangles represent functions, ovals represent types, rounded rectangles represent modules and the single hexagon represents the function which called Build. Black-colored shapes mark functions and types that were called/resolved without an error. Gray-colored nodes mark functions and types that could have been called/resolved in the container but were left unused. Here is an example Graphviz rendering of a dependency graph build which failed: Graphviz Error Example Graphviz DOT files can be converted into SVG’s for viewing in a web browser using the dot command-line tool, ex:
Many other tools including some IDEs support working with DOT files.