tinydi

package module
v0.0.0-...-82886eb Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2024 License: MIT Imports: 3 Imported by: 0

README

tinydi

Usage

You can either create a new context, using tinydi.New(), or use nil in place of it, to use the default context.

Tags

Make sure to annotate your sub-dependencies with `di:"inject"`

Code example
package main

import "fmt"
import "github.com/imthatgin/tinydi"

type HelloService struct {
	World    *WorldService `di:"inject"`
	HelloMap map[string]string
}

func (s *HelloService) Hello() string {
	return fmt.Sprintf("Hello %s", s.World.World())
}

type WorldService struct {
	value   string
}

func (s *WorldService) World() string {
	return s.value
}

func main() {
    i := tinydi.New() // use a nil value in place of i if you wish to use the global, default context.
    
    tinydi.Add[HelloService](i, func(i *tinydi.Injector) *HelloService {
        return &HelloService{}
    })
    tinydi.Add[WorldService](i, func(i *tinydi.Injector) *WorldService {
        return &WorldService{
            value: "World",
        }
    })
    
    h := tinydi.MustGet[HelloService](i)
    
    h.Hello()
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Add

func Add[T any](inj *Injector, provider func(i *Injector) *T)

Add defines a transient service of type T to be included in the DI context. When a service is registered using Add, it will create a new instance every time. If you specify a nil value as the injector instance, it will use the default, global one.

func AddSingleton

func AddSingleton[T any](inj *Injector, provider func(i *Injector) *T)

AddSingleton defines a singleton service of type T to be included in the DI context. When a service is registered using AddSingleton, it will return the same instance every time. If you specify a nil value as the injector instance, it will use the default, global one.

func MustGet

func MustGet[T any](i *Injector) *T

MustGet will provide the dependency, or panic. If you specify a nil value as the injector instance, it will use the default, global one.

Types

type Injector

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

func New

func New() *Injector

New returns a new Injector context, which can be used to separate different injector contexts.

Jump to

Keyboard shortcuts

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