ioc

package module
v1.3.1-0...-3edb43f Latest Latest
Warning

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

Go to latest
Published: Aug 29, 2021 License: MIT Imports: 3 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Container

A lightweight yet powerful IoC container for Go projects. It provides a simple, fluent and easy-to-use interface to make dependency injection in GoLang easier.

Documentation

Required Go Versions

It requires Go v1.15 or newer versions.

Installation

To install this package, run the following command in the root of your project.

go get github.com/wojciech-malota-wojcik/ioc
Introduction

GoLobby Container like any other IoC container is used to bind abstractions to their implementations. Binding is a process of introducing an IoC container that which concrete (implementation) is appropriate for an abstraction. In this process, you also determine how it must be resolved, singleton or transient. In singleton binding, the container provides an instance once and returns it for each request. In transient binding, the container always returns a brand new instance for each request. After the binding process, you can ask the IoC container to get the appropriate implementation of the abstraction that your code depends on. In this case, your code depends on abstractions, not implementations.

Binding
Singleton

Singleton binding using Container:

c := ioc.New()
c.Singleton(func() Abstraction {
  return Implementation
})

It takes a resolver function which its return type is the abstraction and the function body configures the related concrete (implementation) and returns it.

Example for a singleton binding:

c := ioc.New()
c.Singleton(func() Database {
  return &MySQL{}
})
Transient

Transient binding is also similar to singleton binding.

Example for a transient binding:

c := ioc.New()
c.Transient(func() Shape {
  return &Rectangle{}
})
Resolving

Container resolves the dependencies with the method make().

Using References

One way to get the appropriate implementation you need is to declare an instance of the abstraction type and pass its reference to Container this way:

c := ioc.New()
var a Abstraction
c.Resolve(&a)
// "a" will be implementation of the Abstraction

Example:

c := ioc.New()
var m Mailer
c.Resolve(&m)
m.Send("info@miladrahimi.com", "Hello Milad!")
Using Closures

Another way to resolve the dependencies is by using a function (receiver) that its arguments are the abstractions you need. Container will invoke the function and pass the related implementations for each abstraction.

c := ioc.New()
c.Resolve(func(a Abstraction) {
  // "a" will be implementation of the Abstraction
})

Example:

c := ioc.New()
c.Resolve(func(db Database) {
  // "db" will be the instance of MySQL
  db.Query("...")
})

You can also resolve multiple abstractions this way:

c := ioc.New()
c.Resolve(func(db Database, s Shape) {
  db.Query("...")
  s.Area()
})
Calling functions and getting results

You may call a function and get returned values:

c := ioc.New()
var result int
var err error
c.Call(func(db Database) (int, error) {
  return db.GetIntValue("...")
}, &result, &int)
Named bindings

You can also use named bindings to create many bindings of the same type:

c := ioc.New()
c.SingletonNamed("concreteFactoryA", func() Factory {
	return &ConcreteFactoryA{}
})
c.SingletonNamed("concreteFactoryB", func() Factory {
    return &ConcreteFactoryB{}
})

Then you may easily retrieve concrete factory based on a string saved ex. in DB:

c := ioc.New()
var factory Factory
c.ResolveNamed(factoryName, &factory)

You can also easily iterate over all named bindings of particular interface:

c.ForEachNamed(func(factory Factory)) {
    
}

It's possible to get list off all the names used for named bindings for a type:

names := c.Names((*Factory)(nil))

Keep in mind, you have to pass pointer to interface!

Binding time

You can also resolve a dependency at the binding time in your resolver function like the following example.

c := ioc.New()

// Bind Config to JsonConfig
c.Singleton(func() Config {
    return &JsonConfig{...}
})

// Bind Database to MySQL
c.Singleton(func(c Config) Database {
    // "c" will be the instance of JsonConfig
    return &MySQL{
        Username: c.Get("DB_USERNAME"),
        Password: c.Get("DB_PASSWORD"),
    }
})

Notice: You can only resolve the dependencies in a binding resolver function that has already bound.

Sub containers

You may create sub container:

c := ioc.New()
c.Singleton(func() Binding1 { ... })
subC := c.SubContainer()
subC.Singleton(func() Binding2 { ... })

In above case these work:

var binding1 Binding1
var binding2 Binding2
c.Resolve(&binding1)
subC.Resolve(&binding1)
subC.Resolve(&binding2)

This doesn't work:

var binding2 Binding2
c.Resolve(&binding2)

because Binding2 is registered only in sub container.

Usage Tips
Performance

The package Container inevitably uses reflection in binding and resolving processes. If performance is a concern, you should use this package more carefully. Try to bind and resolve the dependencies out of the processes that are going to run many times (for example, on each request), put it where that run only once when you run your applications like main and init functions.

License

GoLobby Container is released under the MIT License.

Documentation

Overview

Package ioc provides an IoC container for Go projects. It provides simple, fluent and easy-to-use interface to make dependency injection in GoLang easier.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Container

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

Container is a IoC container

func New

func New() *Container

New returns a new instance of Container

func (*Container) Call

func (c *Container) Call(function interface{}, returnedValues ...interface{})

Call will call the given function and return its returned values.

func (*Container) ForEachNamed

func (c *Container) ForEachNamed(function interface{})

ForEachNamed iterates over all named concretes

func (*Container) Names

func (c *Container) Names(example interface{}) []string

Names returns names of all the named bindings for the type

func (*Container) Reset

func (c *Container) Reset()

Reset will reset the container and remove all the bindings.

func (*Container) Resolve

func (c *Container) Resolve(receiver interface{})

Resolve will resolve the dependency and return an appropriate concrete of the given abstraction. It can take an abstraction (interface reference) and fill it with the related implementation. It also can takes a function (receiver) with one or more arguments of the abstractions (interfaces) that need to be resolved, Container will invoke the receiver function and pass the related implementations.

func (*Container) ResolveNamed

func (c *Container) ResolveNamed(name string, receiver interface{})

ResolveNamed will resolve the named dependency and return an appropriate concrete of the given abstraction. It can take an abstraction (interface reference) and fill it with the related implementation. It also can takes a function (receiver) with one or more arguments of the abstractions (interfaces) that need to be resolved, Container will invoke the receiver function and pass the related implementations.

func (*Container) Singleton

func (c *Container) Singleton(resolver interface{})

Singleton will bind an abstraction to a concrete for further singleton resolves. It takes a resolver function which returns the concrete and its return type matches the abstraction (interface). The resolver function can have arguments of abstraction that have bound already in Container.

func (*Container) SingletonNamed

func (c *Container) SingletonNamed(name string, resolver interface{})

SingletonNamed will bind a named abstraction to a concrete for further singleton resolves. It takes a resolver function which returns the concrete and its return type matches the abstraction (interface). The resolver function can have arguments of abstraction that have bound already in Container.

func (*Container) SubContainer

func (c *Container) SubContainer() *Container

SubContainer creates sub container Bindings are resolved in sub container first and if it's not possible request is redirected to the parent one

func (*Container) Transient

func (c *Container) Transient(resolver interface{})

Transient will bind an abstraction to a concrete for further transient resolves. It takes a resolver function which returns the concrete and its return type matches the abstraction (interface). The resolver function can have arguments of abstraction that have bound already in Container.

func (*Container) TransientNamed

func (c *Container) TransientNamed(name string, resolver interface{})

TransientNamed will bind a named abstraction to a concrete for further transient resolves. It takes a resolver function which returns the concrete and its return type matches the abstraction (interface). The resolver function can have arguments of abstraction that have bound already in Container.

Jump to

Keyboard shortcuts

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