Dependency Injection

    Dependency injection is the process of one object providing arguments to another. In Hemlock, these dependencies are stored within the main Application container.

    Adding Dependencies

    There are three methods that can be used to add dependencies to the app container, each catering to slightly different use cases.


    The Bind method binds a constructor function to the container that be used to create instances of a specific type. Whenever the type is requested from the container, the function will be called and a new instance will be returned.

    app.Bind(func(app *hemlock.Application) (*MyType, error) {
    	return &MyType{}, nil


    For long-lived objects like database connections, the Singleton binding is more appropriate. When something is bound as a singleton, only the first access will create a new instance. All subsequent requests for that type will return a cached value.

    app.Singleton(func(app *hemlock.Application) (*sql.DB, error) {
        c, err := sql.Open(os.GetEnv("DB_URL"))
    	return c, err


    For scenarios where an instance is already available, the Instance method can be used to bind a value directly.


    Resolving Types

    Types can be accessed (resolved) from the container in two ways.

    The Resolve method can set the value of pointer.

    var c http.Client
    // Use c here

    The ResolveInto method can automatically fill function arguments using values from the container.

    app.ResolveInto(func(c *http.Client) {
    	// Use c here