GO Dependency Injection

KInit

Go Reference codecov Report Card Mentioned in Awesome Go

Usage examples

Installation

go get github.com/go-kata/kinit

Status

This is a beta version. API is not stabilized for now.

Versioning

Till the first major release minor version (v0.x.0) must be treated as a major version and patch version (v0.0.x) must be treated as a minor version.

For example, changing of version from v0.1.0 to v0.1.1 indicates compatible changes, but when version changes v0.1.1 to v0.2.0 this means that the last version breaks the API.

How to use

This library provides the global IoC container which does the automatic Dependency Injection:

kinit.Global()

If you need a local one (e.g. for tests), you can create it as following:

ctr := kinit.NewContainer()

A local container must be filled up with constructors and processors manually whereas the global one can be filled up when initializing packages.

Constructors

Constructors are entities that create objects (dependencies for injection in context of the DI). They have the following interface:

type Constructor interface {
	
	Type() reflect.Type
	
	Parameters() []reflect.Type
	
	Create(a ...reflect.Value) (reflect.Value, kdone.Destructor, error)
	
}

Here Type returns a type of object to create, Parameters returns types of other objects required to create this object and finally Create creates and returns a new object and its destructor (usekdone.Noop, not nil, if object has no destructor).

To register a constructor in the container use the Provide method.

The container allows to have only one constructor for each type. However, the reflect.Type is the interface, and you can implement it as you want, e.g. as following:

type NamedType stuct {
	reflect.Type
	Name string
}

Just keep in mind that the container uses a simple comparison of reflect.Type instances when looks up for necessary constructors (as well as processors and already created objects).

Processors

Processors are entities that process already created objects. The container applies processors immediately after the object creation and before an object will be injected as a dependency at the first time. Processors have the following interface:

type Processor interface {
	
	Type() reflect.Type
	
	Parameters() []reflect.Type

	Process(obj reflect.Value, a ...reflect.Value) error
	
}

Here Type returns a type of object to process, Parameters returns types of other objects required to process this object and finally Process processes an object.

To register a processor in the container use the Attach method.

The container allows to have an unlimited number of processors for each type but doesn't guarantee the order of their calling.

Functors

Functors represent functions to be run in the container and have the following interface:

type Functor interface {
	
	Parameters() []reflect.Type
	
	Call(a ...reflect.Value) ([]Functor, error)
	
}

Here Parameters returns types of objects required to call a function and Call calls a function and may return further functors.

To run functors in the container use the Run method.

At the start of run the container creates so-called arena that holds all created objects (only one object for each type). If some object required as a dependency is already on the arena it will be used, otherwise it will be firstly created and processed. All objects that are on the arena at the end of run will be automatically destroyed.

The container runs given functors sequentially. Their dependencies are resolved recursively using registered constructors and processors. If functor (let's call it branched) returns further functors, the container runs all of them before continue running functors following the branched one. This is called the Depth-First Run.

KInitX

Go Reference

This subpackage provides the expansion set includes default handy implementations of main library interfaces along with other handy tools. In most cases the KInitX is all you need to use the entire KInit functionality.

There are following implementations:

Constructor represents a constructor based on a function. It accepts func(...) T, func(...) (T, error) and func(...) (T, kdone.Destructor, error) signatures where T is an arbitrary Go type.

kinitx.MustProvide(func(config *Config) (*Object, kdone.Destructor, error) { ... })

Opener represents a constructor based on a function that creates an implementation of the io.Closer interface. It accepts func(...) C and func(...) (C, error) signatures where C is an arbitrary implementation of the io.Closer interface.

kinitx.MustProvide(func(logger *log.Logger) (*sql.DB, error) { ... })

Initializer represents a memberwise initializer of a struct. It accepts a template struct like a YourType{} and a template struct pointer like a (*YourType)(nil) or new(YourType).

kinitx.MustProvide((*Config)(nil))

Binder represents a pseudo-constructor that casts an object to an interface. It accepts an interface pointer like a (*YourInterface)(nil).

kinitx.MustBind((*StorageInterface)(nil), (*PostgresStrorage)(nil))

Processor represents a processor based on a function. It accepts func(T, ...) and func(T, ...) error signatures where T is an arbitrary Go type.

kinitx.MustAttach((*Object).SetOptionalProperty)

Functor represents a functor based on a function. It accepts func(...), func(...) error, func(...) (kinit.Functor, error) and func(...) ([]kinit.Functor, error) signatures.

kinitx.MustRun(func(app *Application) error { ... })

KInitQ

Go Reference

The DI mechanism provided by the main library is reflection-based and works in the runtime. However, this subpackage makes it possible to validate the dependency graph semi-statically thanks to build tags.

Just add two main functions as following:

main.go

// +build !inspect

package main

import "github.com/go-kata/kinit/kinitx"

func main() { kinitx.MustRun(EntryPoint) }

main_inspect.go

// +build inspect

package main

import "github.com/go-kata/kinit/kinitx"

func main() { kinitx.MustInspect(nil) }

Now to validate the dependency graph of your program just run:

go run -tags inspect

Example output:

2 errors occurred:
    #1 πŸ – cyclic dependency: *config.Config πŸ – config.Loader πŸ – *config.FileLoader πŸ – *config.Config
    #2 πŸ – unsatisfied dependency: *sql.DB πŸ – *log.Logger

For more details learn the documentation and explore examples.

Putting all together

In the github.com/go-kata/examples repository you can find examples of how may the code uses this library looks like.

References

KDone is the library that provides tools for destroying objects.

KError is the library that provides tools for handling errors.

Owner
GO Kata
GO Development Kit
GO Kata
Similar Resources

A dependency injection library that is focused on clean API and flexibility

Dependency injection DI is a dependency injection library that is focused on clean API and flexibility. DI has two types of top-level abstractions: Co

Oct 13, 2022

golang-runtime-di is a framework for runtime dependency injection in go

golang-runtime-di description golang-runtime-di is a framework for runtime dependency injection in go. usage quickstart add it to your go.mod: go get

Aug 1, 2022

Golang PE injection on windows

GoPEInjection Golang PE injection on windows See: https://malwareunicorn.org/workshops/peinjection.html Based on Cryptowall's PE injection technique.

Jan 6, 2023

two scripts written in golang that will help you recognize dependency confusion.

two scripts written in golang that will help you recognize dependency confusion.

two scripts written in golang that will help you recognize dependency confusion.

Mar 3, 2022

hiboot is a high performance web and cli application framework with dependency injection support

Hiboot - web/cli application framework About Hiboot is a cloud native web and cli application framework written in Go. Hiboot is not trying to reinven

Nov 20, 2022

An additive dependency injection container for Golang.

Alice Alice is an additive dependency injection container for Golang. Philosophy Design philosophy behind Alice: The application components should not

Oct 16, 2022

πŸ›  A full-featured dependency injection container for go programming language.

DI Dependency injection for Go programming language. Tutorial | Examples | Advanced features Dependency injection is one form of the broader technique

Dec 31, 2022

A reflection based dependency injection toolkit for Go.

βš’οΈ dig A reflection based dependency injection toolkit for Go. Good for: Powering an application framework, e.g. Fx. Resolving the object graph during

Jan 1, 2023

Go Dependency Injection Framework

Dingo Dependency injection for go Hello Dingo Dingo works very very similiar to Guice Basically one binds implementations/factories to interfaces, whi

Dec 25, 2022

A dependency injection based application framework for Go.

πŸ¦„ Fx An application framework for Go that: Makes dependency injection easy. Eliminates the need for global state and func init(). Installation We rec

Jan 3, 2023

Simple Dependency Injection Container

Simple Dependency Injection Container

πŸͺ£ gocontainer gocontainer - Dependency Injection Container πŸ“– ABOUT Contributors: RafaΕ‚ Lorenz Want to contribute ? Feel free to send pull requests!

Sep 27, 2022

Simple and yet powerful Dependency Injection for Go

Simple and yet powerful Dependency Injection for Go

goioc/di: Dependency Injection Why DI in Go? Why IoC at all? I've been using Dependency Injection in Java for nearly 10 years via Spring Framework. I'

Dec 28, 2022

Dependency Injection and Inversion of Control package

Linker Linker is Dependency Injection and Inversion of Control package. It supports the following features: Components registry Automatic dependency i

Sep 27, 2022

Strict Runtime Dependency Injection for Golang

wire Wire is runtime depedency injection/wiring for golang. It's designed to be strict to avoid your go application running without proper dependency

Sep 27, 2022

Minimalistic, pluggable Golang evloop/timer handler with dependency-injection

Anagent Minimalistic, pluggable Golang evloop/timer handler with dependency-injection - based on codegangsta/inject - go-macaron/inject and chuckpresl

Sep 27, 2022

Compile-time dependency injection for Go

Dihedral Dihedral is a compile-time injection framework for Go. Getting started go get -u github.com/dimes/dihedral Create a type you want injected

Jun 1, 2022

The fastest HTTP/2 Go Web Framework. AWS Lambda, gRPC, MVC, Unique Router, Websockets, Sessions, Test suite, Dependency Injection and more. A true successor of expressjs and laravel | θ°’θ°’ https://github.com/kataras/iris/issues/1329 |

The fastest HTTP/2 Go Web Framework. AWS Lambda, gRPC, MVC, Unique Router, Websockets, Sessions, Test suite, Dependency Injection and more. A true successor of expressjs and laravel | θ°’θ°’ https://github.com/kataras/iris/issues/1329 |

News This is the under-development branch. Stay tuned for the upcoming release v12.2.0. Looking for a stable release? Head over to the v12.1.8 branch

Dec 28, 2022

Compile-time Dependency Injection for Go

Wire: Automated Initialization in Go Wire is a code generation tool that automates connecting components using dependency injection. Dependencies betw

Jan 2, 2023

Generated dependency injection containers in go (golang)

Generated dependency injection containers in go (golang)

Generation of dependency injection containers for go programs (golang). Dingo is a code generator. It generates dependency injection containers based

Dec 22, 2022
A reflection based dependency injection toolkit for Go.

βš’οΈ dig A reflection based dependency injection toolkit for Go. Good for: Powering an application framework, e.g. Fx. Resolving the object graph during

Jan 1, 2023
Go Dependency Injection Framework

Dingo Dependency injection for go Hello Dingo Dingo works very very similiar to Guice Basically one binds implementations/factories to interfaces, whi

Dec 25, 2022
A dependency injection based application framework for Go.

?? Fx An application framework for Go that: Makes dependency injection easy. Eliminates the need for global state and func init(). Installation We rec

Jan 3, 2023
Simple Dependency Injection Container
Simple Dependency Injection Container

?? gocontainer gocontainer - Dependency Injection Container ?? ABOUT Contributors: RafaΕ‚ Lorenz Want to contribute ? Feel free to send pull requests!

Sep 27, 2022
Simple and yet powerful Dependency Injection for Go
Simple and yet powerful Dependency Injection for Go

goioc/di: Dependency Injection Why DI in Go? Why IoC at all? I've been using Dependency Injection in Java for nearly 10 years via Spring Framework. I'

Dec 28, 2022
Dependency Injection and Inversion of Control package

Linker Linker is Dependency Injection and Inversion of Control package. It supports the following features: Components registry Automatic dependency i

Sep 27, 2022
Strict Runtime Dependency Injection for Golang

wire Wire is runtime depedency injection/wiring for golang. It's designed to be strict to avoid your go application running without proper dependency

Sep 27, 2022
Compile-time dependency injection for Go

Dihedral Dihedral is a compile-time injection framework for Go. Getting started > go get -u github.com/dimes/dihedral Create a type you want injected

Jun 1, 2022
Compile-time Dependency Injection for Go

Wire: Automated Initialization in Go Wire is a code generation tool that automates connecting components using dependency injection. Dependencies betw

Jan 2, 2023
Generated dependency injection containers in go (golang)
Generated dependency injection containers in go (golang)

Generation of dependency injection containers for go programs (golang). Dingo is a code generator. It generates dependency injection containers based

Dec 22, 2022