goweb/service/container.go

48 lines
1.1 KiB
Go
Raw Permalink Normal View History

// Package service -
// Propose une implémentation
// simple d'un conteneur de service afin de permettre
// l'injection de dépendances dans les applications web
2018-12-06 15:18:05 +01:00
package service
import (
"errors"
)
var (
// ErrNotImplemented is the error when a service is accessed
// and no implementation was provided
ErrNotImplemented = errors.New("service not implemented")
)
// Provider is a provider for a service
type Provider func(ctn *Container) (interface{}, error)
// Container is a simple service container for dependency injection
type Container struct {
providers map[Name]Provider
}
// Name is a name of a service
type Name string
// Provide registers a provider for the survey.Service
func (c *Container) Provide(name Name, provider Provider) {
c.providers[name] = provider
}
// Service retrieves a service implementation based on its name
func (c *Container) Service(name Name) (interface{}, error) {
provider, exists := c.providers[name]
if !exists {
return nil, ErrNotImplemented
}
return provider(c)
}
// NewContainer returns a new empty service container
func NewContainer() *Container {
return &Container{
providers: make(map[Name]Provider),
}
}