comments about the service locator

This commit is contained in:
maddalax 2024-10-25 22:06:58 -05:00
parent 3468baaa84
commit 2f35c08afd

View file

@ -24,6 +24,13 @@ type Locator struct {
mutex sync.RWMutex mutex sync.RWMutex
} }
// NewLocator creates a new locator to register services
// Usage:
//
// locator := service.NewLocator()
// service.Set[db.Queries](locator, service.Singleton, db.Provide)
//
// service.Get[db.Queries](locator)
func NewLocator() *Locator { func NewLocator() *Locator {
return &Locator{ return &Locator{
services: make(map[string]Provider), services: make(map[string]Provider),
@ -44,6 +51,9 @@ func (l *Locator) getCache(key string) any {
return l.cache[key] return l.cache[key]
} }
// Get returns a service from the locator
// If the service is not found, log.Fatalf is called
// If the service is a singleton, it will be cached after first invocation
func Get[T any](locator *Locator) *T { func Get[T any](locator *Locator) *T {
locator.mutex.RLock() locator.mutex.RLock()
i := new(T) i := new(T)
@ -70,6 +80,8 @@ func Get[T any](locator *Locator) *T {
return cb return cb
} }
// Set registers a service with the locator
// If the service is a singleton, it will be cached after first invocation of Get
func Set[T any](locator *Locator, lifecycle Lifecycle, value func() *T) { func Set[T any](locator *Locator, lifecycle Lifecycle, value func() *T) {
t := reflect.TypeOf(value) t := reflect.TypeOf(value)
rt := t.Out(0) rt := t.Out(0)