dscope

package module
v0.0.0-...-552d8d2 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 11 Imported by: 52

README

dscope - A Dependency Injection Library for Go

dscope is a powerful and flexible dependency injection library for Go, designed to promote clean architecture, enhance testability, and manage dependencies with ease. It emphasizes immutability, lazy initialization, and type safety.

Why use dscope?

Managing dependencies in larger Go applications can become complex. dscope offers several advantages:

  • Type-Safe Dependencies: Leverages Go's type system to ensure that dependencies are resolved correctly at compile time or with clear runtime panics if a type is missing. Generic methods like scope.Get[T]() provide compile-time type checking for retrievals.
  • Define and Depend on Interfaces (or Concrete Types): While you can register and request concrete types directly, dscope fully supports defining providers that return interfaces and requesting dependencies via those interfaces, promoting loose coupling.

Core Concepts

Scope

A Scope is an immutable container holding definitions for various types. It's the central piece from which you resolve dependencies. The Universe is the initial empty scope.

Definitions

Definitions are functions or pointers that tell a scope how to create or provide an instance of a type.

  • Provider Functions: Functions that return one or more values. Their arguments are themselves resolved as dependencies from the scope.
    func NewMyService(db Database) MyService { /* ... */ }
    func NewConfigAndLogger() (Config, Logger) { /* ... */ }
    
  • Pointer Values: Pointers to existing instances can also be used as definitions. The pointed-at value will be provided.
    cfg := &MyConfig{Value: "example"}
    scope := dscope.New(cfg) // MyConfig is now available
    
Fork

Fork is the primary mechanism for creating new scopes. When you Fork an existing scope, you create a new scope that contains every definition of the original, with the new definitions layered on top. The two scopes are independent branches: you can add new definitions or override existing ones in the new scope without affecting the original.

baseScope := dscope.New(func() int { return 42 })
branch1 := baseScope.Fork(func() string { return "hello" }) // same int as base, adds string
branch2 := baseScope.Fork(func() int { return 100 })   // overrides int
Reset

Reset creates a new scope in which every provider result is recomputed lazily on the next access. The original scope is unaffected.

calls := 0
scope := dscope.New(func() int {
	calls++
	return calls
})
fmt.Println(scope.Get[int]())      // Output: 1
fmt.Println(scope.Get[int]())      // Output: 1 (result is cached)

resetScope := scope.Reset()
fmt.Println(resetScope.Get[int]()) // Output: 2 (recomputed)

dscope.Reset (type Reset func() Scope) is also provided as a built-in dependency bound to the current scope's Reset method, so it can be injected into providers, similar to dscope.Fork:

reset := scope.Get[dscope.Reset]()
// reset() returns a reset scope of the current scope
resetScope := reset()

Basic Usage Examples

1. Creating a New Scope

You can create a new scope from scratch using dscope.New() (which is equivalent to dscope.Universe.Fork()).

package main

import (
	"fmt"
	"github.com/reusee/dscope"
)

// Define some types
type Greeter string
type Message string

// Define provider functions
func provideGreeter() Greeter {
	return "Hello"
}

func provideMessage(g Greeter) Message {
	return Message(fmt.Sprintf("%s, dscope!", g))
}

func main() {
	scope := dscope.New(
		provideGreeter,
		provideMessage,
	)
	// Scope is now configured
}
2. Getting Values by Type

You can retrieve values from the scope using scope.GetType(reflect.Type), the generic scope.Get[T](), or scope.Assign(&target).

  • scope.Get[T]() (Recommended for type safety):

    msg := scope.Get[Message]()
    fmt.Println(msg) // Output: Hello, dscope!
    
  • scope.TryGet[T]() (Non-panicking lookup): returns the value and whether the type is defined in the scope, instead of panicking on a missing type.

    if msg, ok := scope.TryGet[Message](); ok {
        fmt.Println(msg) // Output: Hello, dscope!
    }
    
  • scope.Assign(&target):

    var m Message
    var g Greeter
    scope.Assign(&m)
    scope.Assign(&g)
    fmt.Println(g, m) // Output: Hello Hello, dscope!
    
  • scope.GetType(reflect.Type) / scope.TryGetType(reflect.Type) (reflection-based lookup; GetType panics on a missing type):

    import "reflect"
    // ...
    msgVal, ok := scope.TryGetType(reflect.TypeOf(Message("")))
    if ok {
        fmt.Println(msgVal.Interface().(Message))
    }
    
3. Computing Values in a Scope

A computation is a provider: fork the computing function and get its result type. Fork resolves the function's parameters from the scope, and the returned values become types of the new scope.

type Salutation string

func provideSalutation() Salutation {
	return "Greetings"
}

scope = scope.Fork(provideSalutation) // Add Salutation to the scope

finalMsg := scope.Fork(func(s Salutation, m Message) string {
	return fmt.Sprintf("%s! %s", s, m)
}).Get[string]()

fmt.Println(finalMsg) // Output: Greetings! Hello, dscope!
4. Forking a Scope

Forking creates a new scope that contains the original's definitions, allowing you to add or override definitions.

baseScope := dscope.New(func() int { return 10 })

// Fork 1: Add a new type
branch1 := baseScope.Fork(func(i int) string {
	return fmt.Sprintf("Number: %d", i)
})
fmt.Println(branch1.Get[string]()) // Output: Number: 10

// Fork 2: Override an existing type
branch2 := baseScope.Fork(func() int { return 20 })
fmt.Println(branch2.Get[int]()) // Output: 20

// Original scope is unaffected
fmt.Println(baseScope.Get[int]()) // Output: 10
5. Modules

Modules help organize definitions. You can embed dscope.Module in your structs and then use dscope.Methods(moduleInstances...) to add all exported methods of those instances (and their embedded modules) as providers to the scope.

type DBConnection string
type MyService string

type DatabaseModule struct {
	dscope.Module
}

func (dbm *DatabaseModule) ProvideDBConnection() DBConnection { // Becomes a provider
	return "db_connection_string"
}

type ServiceModule struct {
	dscope.Module
	DBDep DatabaseModule // Module field's methods will also be added
}

func (sm *ServiceModule) ProvideMyService(dbConn DBConnection) MyService { // Becomes a provider
	return MyService("service_using_" + string(dbConn))
}

func main() {
	// Using concrete instance
	scope := dscope.New(
		dscope.Methods(new(ServiceModule))...,
	)
	service := scope.Get[MyService]()
	fmt.Println(service)
}

Output:

service_using_db_connection_string

A struct that embeds dscope.Module can also be passed directly to New or Fork: the scope expands it into its methods automatically.

6. Struct Field Injection

dscope can inject dependencies into the fields of a struct.

  • Using dscope:"." or dscope:"inject" tag:

    type MyStruct struct {
        Dep1 Greeter `dscope:"."` // or dscope:"inject"
        Dep2 Message `dscope:"."`
    }
    
    scope := dscope.New(provideGreeter, provideMessage)
    var myInstance MyStruct
    // The scope provides InjectStruct; retrieve it and call it on the target:
    scope.InjectStruct(&myInstance)
    
    
    fmt.Printf("Injected: Greeter='%s', Message='%s'\n", myInstance.Dep1, myInstance.Dep2)
    // Output: Injected: Greeter='Hello', Message='Hello, dscope!'
    
  • Using dscope.Inject[T] for lazy field injection: Fields of type dscope.Inject[T] are populated with a function that, when called, resolves T from the scope. This is useful for optional dependencies or dependencies needed much later.

    type AnotherStruct struct {
        LazyGreeter dscope.Inject[Greeter]
        RegularMsg  Message `dscope:"."`
    }
    
    scope := dscope.New(provideGreeter, provideMessage)
    var anotherInstance AnotherStruct
    scope.InjectStruct(&anotherInstance)
    
    fmt.Printf("Regular Message: %s\n", anotherInstance.RegularMsg)
    // LazyGreeter is not resolved yet.
    // To get the greeter:
    actualGreeter := anotherInstance.LazyGreeter()
    fmt.Printf("Lazy Greeter: %s\n", actualGreeter)
    // Output:
    // Regular Message: Hello, dscope!
    // Lazy Greeter: Hello
    

This covers the core features and usage patterns of dscope. Its design promotes modularity and testability in Go applications.

Documentation

Index

Constants

View Source
const TheoryOfConstructors = `` /* 1150-byte string literal not displayed */
View Source
const TheoryOfLazyInitialization = `` /* 743-byte string literal not displayed */
View Source
const TheoryOfModuleMethodDiscovery = `` /* 1445-byte string literal not displayed */

TheoryOfModuleMethodDiscovery documents how Methods expands a module object into provider functions and which inputs are rejected.

View Source
const TheoryOfModules = `` /* 791-byte string literal not displayed */

TheoryOfModules documents the module pattern: grouping providers as methods on a struct that embeds dscope.Module.

View Source
const TheoryOfScopeAssignment = `` /* 826-byte string literal not displayed */
View Source
const TheoryOfScopeCore = `` /* 937-byte string literal not displayed */

TheoryOfScopeCore documents the fundamental model of dscope: an immutable, type-keyed container of lazily evaluated definitions.

View Source
const TheoryOfScopeDefinitions = `` /* 927-byte string literal not displayed */
View Source
const TheoryOfScopeFork = `` /* 1199-byte string literal not displayed */

TheoryOfScopeFork documents the semantics and typical uses of Fork.

View Source
const TheoryOfScopeForkFlatten = `` /* 1083-byte string literal not displayed */
View Source
const TheoryOfScopeIdentity = `` /* 987-byte string literal not displayed */
View Source
const TheoryOfScopeInjectStruct = `` /* 778-byte string literal not displayed */

TheoryOfScopeInjectStruct documents struct field injection: how fields are selected and resolved.

View Source
const TheoryOfScopeReset = `` /* 425-byte string literal not displayed */

TheoryOfScopeReset documents the semantics and typical use of Reset.

View Source
const TheoryOfTypeGranularity = `` /* 432-byte string literal not displayed */

Variables

View Source
var ErrBadArgument = errors.New("bad argument")
View Source
var ErrBadDefinition = errors.New("bad definition")
View Source
var ErrDependencyLoop = errors.New("dependency loop")
View Source
var ErrDependencyNotFound = errors.New("dependency not found")
View Source
var Universe = Scope{}

Universe is the empty root scope.

Functions

func Methods

func Methods(objects ...any) (ret []any)

func Provide

func Provide[T any](v T) *T

Provide is a helper that returns a pointer to a value, suitable for use as a definition in a Scope. The value is copied when the scope is created.

Types

type Fork

type Fork func(defs ...any) Scope

Fork is the type of a scope's Fork method, bound to the scope that provides it. It is always provided as a built-in dependency.

type Inject

type Inject[T any] func() T

type InjectStruct

type InjectStruct func(target any)

type Module

type Module struct{}

type Reset

type Reset func() Scope

Reset is the type of a scope's Reset method, bound to the scope that provides it. It is always provided as a built-in dependency.

type Scope

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

Scope represents an immutable dependency injection container.

func New

func New(defs ...any) Scope

New creates a new root Scope with the given definitions.

func (Scope) AllTypes

func (s Scope) AllTypes() iter.Seq[reflect.Type]

func (Scope) Assign

func (scope Scope) Assign[T any](ptr *T)

Assign retrieves the value of type T from the scope and writes it to ptr.

func (Scope) Fork

func (scope Scope) Fork(defs ...any) Scope

func (Scope) Get

func (scope Scope) Get[T any]() (o T)

Get is a type-safe generic method to retrieve a single value of type T.

func (Scope) GetType

func (scope Scope) GetType(typ reflect.Type) reflect.Value

GetType retrieves the value of the given type from the scope as reflect.Value.

func (Scope) InjectStruct

func (scope Scope) InjectStruct(target any)

func (Scope) Reset

func (scope Scope) Reset() Scope

func (Scope) TryGet

func (scope Scope) TryGet[T any]() (o T, ok bool)

TryGet is a type-safe generic method to retrieve a single value of type T.

func (Scope) TryGetType

func (scope Scope) TryGetType(typ reflect.Type) (reflect.Value, bool)

TryGetType retrieves the value of the given type from the scope as reflect.Value.

Jump to

Keyboard shortcuts

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