provider

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 18, 2026 License: MIT Imports: 8 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
  • 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)
}
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 with the manager.
Run Run(ctx context.Context, opts ...Option) error Runs the full lifecycle: register → boot → wait for context cancellation → terminate.
Interfaces
Interface Methods Description
Container Reset(), Bind(...), Call(...), Resolve(...), Fill(...) 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.

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.

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 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.

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.

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.

Jump to

Keyboard shortcuts

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