goweb/service/container.go

44 lines
1013 B
Go
Raw Normal View History

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),
}
}