provider

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 19, 2026 License: MIT Imports: 10 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.

README

Go Reference CI CodeQL Go Report Card Coverage Status

Provider Logo

Provider

Provider is a lightweight service provider manager for Go projects. It manages the full lifecycle of service providers — registration, booting, and graceful termination — on top of a dependency injection container.

Features:

  • Three-phase lifecycle: Register → Boot → Terminate
  • Ordered execution via the optional HasOrder interface
  • Reverse-order termination for clean shutdown
  • Scoped providers that run per request/job inside a child container seeded with WithValue
  • Global instance for small applications
  • Concurrency-safe with no race conditions
  • Works with any Container implementation (e.g. danceable/container)

Documentation

Required Go Versions

It requires Go v1.26 or newer versions.

Installation

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

go get github.com/danceable/provider

Next, include it in your application:

import "github.com/danceable/provider"
Introduction

Provider works by managing the lifecycle of service providers in three ordered phases:

  1. Register — Each provider registers its bindings into the container. Providers are called from lowest order to highest.
  2. Boot — After all providers are registered, each provider is booted (again lowest to highest). This is the place for initialization logic that depends on bindings from other providers.
  3. Terminate — When the context is cancelled the manager terminates every provider in reverse order (highest to lowest), allowing graceful cleanup.

A provider is any type that implements the Provider interface:

type Provider interface {
    Register(ctx context.Context, container Container) error
    Boot(ctx context.Context, container Container) error
    Terminate(ctx context.Context) error
}

Optionally, a provider can implement HasOrder to control its execution priority:

type HasOrder interface {
    Order() int
}

Providers with lower order values execute first during Register and Boot, and last during Terminate.

Quick Start

The following example demonstrates registering and running a single provider.

provider.Register(&MyProvider{})

ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()

if err := provider.Run(ctx); err != nil {
    log.Fatal(err)
}
Examples
Implementing a Provider
type DatabaseProvider struct{}

func (p *DatabaseProvider) Register(ctx context.Context, c provider.Container) error {
    return c.Bind(func() Database {
        return &MySQL{Host: "localhost", Port: 3306}
    }, bind.Singleton())
}

func (p *DatabaseProvider) Boot(ctx context.Context, c provider.Container) error {
    var db Database
    if err := c.Resolve(&db); err != nil {
        return err
    }
    return db.Connect()
}

func (p *DatabaseProvider) Terminate(ctx context.Context) error {
    // cleanup resources
    return nil
}
Global Instance

The package provides a default global Manager instance — exposed as provider.Default — for convenience in small applications. Instead of creating a manager with provider.New(), you can call provider.Register() and provider.Run() directly as package-level functions; they all delegate to provider.Default.

provider.Register(&DatabaseProvider{})
provider.Register(&CacheProvider{})

ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()

if err := provider.Run(ctx); err != nil {
    log.Fatal(err)
}
Custom Manager Instance

For more control, create your own Manager with a specific container.

c := container.New()
m := provider.New(c)

m.Register(&DatabaseProvider{})
m.Register(&CacheProvider{})

ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()

if err := m.Run(ctx); err != nil {
    log.Fatal(err)
}
Ordered Providers

Implement HasOrder to control the execution order. Providers with lower order values are registered and booted first, and terminated last.

type DatabaseProvider struct{}

func (p *DatabaseProvider) Order() int { return 1 }

func (p *DatabaseProvider) Register(ctx context.Context, c provider.Container) error { /* ... */ }
func (p *DatabaseProvider) Boot(ctx context.Context, c provider.Container) error     { /* ... */ }
func (p *DatabaseProvider) Terminate(ctx context.Context) error                      { /* ... */ }

type CacheProvider struct{}

func (p *CacheProvider) Order() int { return 2 }

func (p *CacheProvider) Register(ctx context.Context, c provider.Container) error { /* ... */ }
func (p *CacheProvider) Boot(ctx context.Context, c provider.Container) error     { /* ... */ }
func (p *CacheProvider) Terminate(ctx context.Context) error                      { /* ... */ }

With the above, the execution order is:

  1. DatabaseProvider.Register → CacheProvider.Register
  2. DatabaseProvider.Boot → CacheProvider.Boot
  3. CacheProvider.Terminate → DatabaseProvider.Terminate
Lifecycle

Run blocks until the provided context is cancelled. A typical pattern uses signal.NotifyContext so the application shuts down on an OS signal:

ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel()

if err := provider.Run(ctx); err != nil {
    log.Fatal(err)
}
Run Options

Run accepts functional options to customize termination behavior and register a post-boot callback.

Option Description
WithTerminationDelay(d time.Duration) Duration to wait before starting termination after the context is cancelled. Default: 300ms.
WithTerminationDeadline(d time.Duration) Maximum duration allowed for all providers to terminate. Default: 200ms.
WithCallback(fn func(ctx context.Context, container Container)) Function called (in a goroutine) after all providers have booted but before waiting for the context to be cancelled. Receives both the context and the container.
if err := provider.Run(ctx,
    provider.WithTerminationDelay(1*time.Second),
    provider.WithTerminationDeadline(10*time.Second),
    provider.WithCallback(func(ctx context.Context, c provider.Container) {
        log.Println("all providers booted")
    }),
); err != nil {
    log.Fatal(err)
}
Scoped Providers

Some providers should not live for the whole application — they belong to a single request, job, or transaction. Mark these by implementing the optional HasScope interface (Scoped() bool) and returning true; Register then routes them to the scoped set automatically. Scoped providers are skipped by Run and instead executed each time you open a scope, against a child container derived from the manager's container.

type RequestContextProvider struct{}

func (p *RequestContextProvider) Scoped() bool { return true }

func (p *RequestContextProvider) Register(ctx context.Context, c provider.Container) error { /* ... */ }
func (p *RequestContextProvider) Boot(ctx context.Context, c provider.Container) error     { /* ... */ }
func (p *RequestContextProvider) Terminate(ctx context.Context) error                      { /* ... */ }

Open a scope with Scope(ctx, opts...). By default the scope is anonymous and ephemeral — backed by container.Derive, it is garbage-collected once you drop the returned *Scope, which is ideal per request/job. WithValue(name, value) options seed the child before the scoped providers' Register then Boot run. The returned *Scope exposes the child via Container(); you own its lifetime and must call Terminate when the scope ends (scoped providers terminate in reverse order, just like Run).

m.Register(&RequestContextProvider{}) // routed to the scoped set via Scoped()

// Open a scope for one HTTP request, seeding request-specific values.
scope, err := m.Scope(r.Context(),
    provider.WithValue("requestID", reqID),
    provider.WithValue("user", currentUser),
)
if err != nil {
    return err
}
defer scope.Terminate(r.Context())

// Resolve a seeded value (bound as a named singleton).
var user *User
if err := scope.Container().Resolve(&user, resolve.WithName("user")); err != nil {
    return err
}

Two options change the scope's lifetime:

  • WithPersistent(name) makes the scope a named, persistent child (container.Scope) instead of an ephemeral one. The named child is cached on its parent and reused by later calls with the same name.
  • WithAutoTermination() ties teardown to the context: the scope terminates itself once ctx is cancelled, so you don't have to call Terminate. Termination still runs exactly once, so combining it with an explicit Terminate is safe.
// A persistent scope that cleans itself up when ctx is cancelled.
scope, err := m.Scope(ctx,
    provider.WithPersistent("worker"),
    provider.WithAutoTermination(),
    provider.WithValue("jobID", jobID),
)

Scope is a method on *Manager; reach the global instance via provider.Default.Scope(...).

Manager Methods
Method Signature Description
New New(container Container) *Manager Creates a new manager instance with the given container.
Register Register(provider Provider) Registers a service provider. Providers implementing HasScope and returning true are stored as scoped providers; all others run at global boot.
Run Run(ctx context.Context, opts ...Option) error Runs the full lifecycle: register → boot → wait for context cancellation → terminate.
Scope Scope(ctx, opts ...ScopeOption) (*Scope, error) Opens a scoped instance (ephemeral by default; see options) and returns a handle the caller must Terminate unless WithAutoTermination is set.
Scope Options
Option Description
WithValue(name string, value any) Seeds the scoped container with value, bound as a named singleton and resolvable via resolve.WithName(name). A nil value returns ErrNilScopeValue.
WithPersistent(name string) Makes the scope a named, persistent child (container.Scope) instead of the default ephemeral one (container.Derive).
WithAutoTermination() Terminates the scope automatically once the context passed to Scope is cancelled. Teardown runs exactly once.
Interfaces
Interface Methods Description
Container Reset(), Bind(...), Call(...), Resolve(...), Fill(...), Scope(name), Derive() Dependency injection container used by providers to register and resolve bindings.
Provider Register(ctx, container), Boot(ctx, container), Terminate(ctx) Service provider that participates in the managed lifecycle.
HasOrder Order() int Optional interface for providers to specify execution priority. Lower values execute first.
HasScope Scoped() bool Optional interface for providers to opt into scoped execution. Returning true makes Register store the provider as scoped.

The handle returned by Scope is a concrete *Scope:

Type Methods Description
Scope Name() string, Container() Container, Terminate(ctx) error A live scoped instance: the child container plus its booted scoped providers.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Default = New(newAdapter(container.Default))

Default is the default concrete of the service provider manager.

View Source
var ErrNilScopeValue = errors.New("provider: scope value must not be nil")

ErrNilScopeValue is returned when a nil value is passed to WithValue. The container binds values by their reflected type, which cannot be determined from an untyped nil.

Functions

func DefaultOptions

func DefaultOptions() *options

DefaultOptions returns a new instance of options with default values.

func Register

func Register(provider Provider)

Register calls the Register method of the default service provider manager.

func Run

func Run(ctx context.Context, opts ...Option) error

Run calls the Run method of the default service provider manager.

Types

type Container

type Container interface {
	// Reset calls the same method of the default concrete.
	Reset()

	// Bind calls the same method of the default concrete.
	Bind(receiver any, opts ...bind.BindOption) error

	// Call calls the same method of the default concrete.
	Call(receiver any, opts ...resolve.ResolveOption) error

	// Resolve calls the same method of the default concrete.
	Resolve(abstraction any, opts ...resolve.ResolveOption) error

	// Fill calls the same method of the default concrete.
	Fill(receiver any, opts ...resolve.ResolveOption) error

	// Scope creates a new child container with the given name, which can be used to manage scoped dependencies.
	Scope(name string) Container

	// Derive creates a new child container that inherits the binding of the parent container.
	Derive() Container
}

Container defines the interface for a dependency injection container.

type HasOrder

type HasOrder interface {

	// Order determines the execution order of the provider.
	// Providers with lower order values are registered and booted before those with higher values.
	// 1- first register from lower to higher.
	// 2- then boot from lower to higher.
	// 3- finally terminate from higher to lower. (reverse order for termination)
	Order() int
}

HasOrder is an optional interface that providers can implement to specify their execution order.

type HasScope added in v1.1.0

type HasScope interface {

	// Scoped reports whether the provider should be registered as a scoped provider.
	Scoped() bool
}

HasScope is an optional interface that providers can implement to opt into scoped execution. When Register receives a provider whose Scoped method returns true, the provider is run per-scope (by Scope/Derive against a child container) instead of at global boot.

type Manager

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

Manager manages the lifecycle of service providers, including their registration, booting, and termination.

func New

func New(container Container) *Manager

New creates a new instance of the service provider manager with the given container.

func (*Manager) Register

func (m *Manager) Register(provider Provider)

Register registers a service provider with the service provider manager. Providers that implement HasScope and return true are stored as scoped providers (run per-scope); all others run at global boot.

func (*Manager) Run

func (m *Manager) Run(ctx context.Context, opts ...Option) error

Run executes the service provider manager, which involves booting all registered providers and handling their termination.

func (*Manager) Scope added in v1.1.0

func (m *Manager) Scope(ctx context.Context, opts ...ScopeOption) (*Scope, error)

Scope opens a scoped instance of the container and runs the manager's scoped providers against it. By default the scope is anonymous and ephemeral (container.Derive), becoming eligible for garbage collection once the caller drops the returned Scope; WithPersistent makes it a named, persistent child instead. Any WithValue options seed the child before the scoped providers' Register then Boot. The caller owns the returned Scope and must Terminate it when the scope ends, unless WithAutoTermination ties teardown to ctx.

On any error the scope is not returned; matching the manager's global Run, already-booted providers are not terminated here.

type Option

type Option func(*options)

Option is a function that configures the service provider manager.

func WithCallback

func WithCallback(callback func(ctx context.Context, container Container)) Option

WithCallback sets the callback function that will be called with the context and container when the manager starts running.

func WithTerminationDeadline

func WithTerminationDeadline(deadline time.Duration) Option

WithTerminationDeadline sets the duration to wait for providers to terminate before forcing termination.

func WithTerminationDelay

func WithTerminationDelay(delay time.Duration) Option

WithTerminationDelay sets the duration to wait for providers to terminate gracefully before forcing termination.

type Provider

type Provider interface {
	// Register registers the provider's services into the container.
	// This method is called during the application's initialization phase.
	Register(ctx context.Context, container Container) error

	// Boot boots the provider, which is called after all providers have been registered.
	// This method is used to perform any initialization tasks that require access to other providers.
	Boot(ctx context.Context, container Container) error

	// Terminate terminates the provider, which is called before the application exits.
	// This method is used to release resources or perform cleanup tasks.
	Terminate(ctx context.Context) error
}

Provider defines the interface for a service provider.

type Scope added in v1.1.0

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

Scope is a live scoped instance: a child container seeded with the WithValue values and with the manager's scoped providers already registered and booted. Call Terminate to tear the scoped providers down in reverse order (unless WithAutoTermination was set, which does this for you on context cancellation).

func (*Scope) Container added in v1.1.0

func (s *Scope) Container() Container

Container returns the child container backing the scope.

func (*Scope) Name added in v1.1.0

func (s *Scope) Name() string

Name returns the scope name, or an empty string for an ephemeral scope.

func (*Scope) Terminate added in v1.1.0

func (s *Scope) Terminate(ctx context.Context) error

Terminate terminates the scope's providers in reverse order, mirroring the manager's global termination semantics. It is idempotent: only the first call runs the providers' Terminate, and every call returns that run's error.

type ScopeOption added in v1.1.0

type ScopeOption func(*scopeConfig)

ScopeOption configures a scoped instance of the container.

func WithAutoTermination added in v1.1.0

func WithAutoTermination() ScopeOption

WithAutoTermination makes the scope terminate itself once the context passed to Scope is cancelled, releasing the caller from calling Terminate. Teardown runs exactly once, whether triggered by the context or by an explicit Terminate, so combining the two is safe.

func WithPersistent added in v1.1.0

func WithPersistent(name string) ScopeOption

WithPersistent makes the scope a named, persistent child of the manager's container (container.Scope) rather than the default anonymous, ephemeral one (container.Derive). The named child is cached on its parent and reused by later calls with the same name.

func WithValue added in v1.1.0

func WithValue(name string, value any) ScopeOption

WithValue seeds the scoped container with value, resolvable by name. The value is bound as a named singleton, so scoped providers (and anything else resolving from the scope) can retrieve it via resolve.WithName(name).

Jump to

Keyboard shortcuts

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