From 2f35c08afd64ea91557078ae2ce87e1b06bcd438 Mon Sep 17 00:00:00 2001 From: maddalax Date: Fri, 25 Oct 2024 22:06:58 -0500 Subject: [PATCH] comments about the service locator --- framework/service/locator.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/framework/service/locator.go b/framework/service/locator.go index 3cc79d4..f38f70e 100644 --- a/framework/service/locator.go +++ b/framework/service/locator.go @@ -24,6 +24,13 @@ type Locator struct { 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 { return &Locator{ services: make(map[string]Provider), @@ -44,6 +51,9 @@ func (l *Locator) getCache(key string) any { 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 { locator.mutex.RLock() i := new(T) @@ -70,6 +80,8 @@ func Get[T any](locator *Locator) *T { 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) { t := reflect.TypeOf(value) rt := t.Out(0)