di

package
v1.0.32 Latest Latest
Warning

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

Go to latest
Published: Dec 12, 2024 License: Apache-2.0 Imports: 2 Imported by: ? 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.

Documentation

Overview

di implements a simple generic dependency injection container.

Sample usage:

package main

import (
	"fmt"
	"github.com/edgexfoundry/go-mod-bootstrap/v3/di"
)

type foo struct {
	FooMessage string
}

func NewFoo(m string) *foo {
	return &foo{
		FooMessage: m,
	}
}

type bar struct {
	BarMessage string
	Foo        *foo
}

func NewBar(m string, foo *foo) *bar {
	return &bar{
		BarMessage: m,
		Foo:        foo,
	}
}

func main() {
	container := di.NewContainer(
		di.ServiceConstructorMap{
			"foo": func(get di.Get) any {
				return NewFoo("fooMessage")
			},
			"bar": func(get di.Get) any {
				return NewBar("barMessage", get("foo").(*foo))
			},
		})

	b := container.Get("bar").(*bar)
	fmt.Println(b.BarMessage)
	fmt.Println(b.Foo.FooMessage)
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func TypeInstanceToName

func TypeInstanceToName(v any) string

TypeInstanceToName converts an instance of a type to a unique name.

Types

type Container

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

Container is a receiver that maintains a list of services, their constructors, and their constructed instances in a thread-safe manner.

func NewContainer

func NewContainer(serviceConstructors ServiceConstructorMap) *Container

NewContainer is a factory method that returns an initialized Container receiver struct.

func (*Container) Get

func (c *Container) Get(serviceName string) any

Get wraps get to make it thread-safe.

func (*Container) Update

func (c *Container) Update(serviceConstructors ServiceConstructorMap)

Set updates its internal serviceMap with the contents of the provided ServiceConstructorMap.

type Get

type Get func(serviceName string) any

type ServiceConstructor

type ServiceConstructor func(get Get) any

ServiceConstructor defines the contract for a function/closure to create a service.

type ServiceConstructorMap

type ServiceConstructorMap map[string]ServiceConstructor

ServiceConstructorMap maps a service name to a function/closure to create that service.

Jump to

Keyboard shortcuts

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