diff --git a/container.go b/container.go index 6a6d2f6..f0ccd87 100644 --- a/container.go +++ b/container.go @@ -84,8 +84,20 @@ func (c *container) destroy(typ reflect.Type, identifier ...string) { delete(c.instances, instanceSelector) } +func (c *container) destroyAllMatching(match func(string) bool) { + c.mu.Lock() + defer c.mu.Unlock() + + for key := range c.instances { + if match(key) { + delete(c.instances, key) + } + } + println("") +} + func (c *container) getSelector(typ reflect.Type, identifier ...string) string { typeName := typ.String() additionalKey := strings.Join(identifier, "_") - return fmt.Sprintf("%s_%s", typeName, additionalKey) + return fmt.Sprintf("%s_%s", additionalKey, typeName) } diff --git a/injector.go b/injector.go index 2bd8fe5..8b5f9b0 100644 --- a/injector.go +++ b/injector.go @@ -35,3 +35,7 @@ func Destroy[T any](identifier ...string) { typ := reflect.TypeOf((*T)(nil)).Elem() getContainer().destroy(typ, identifier...) } + +func DestroyAllMatching(match func(string) bool) { + getContainer().destroyAllMatching(match) +} diff --git a/injector_test.go b/injector_test.go index 40f4959..70db9f9 100644 --- a/injector_test.go +++ b/injector_test.go @@ -2,6 +2,7 @@ package di_test import ( "fmt" + "strings" "testing" di "git.apihub24.de/admin/generic-di" @@ -211,6 +212,13 @@ func TestOverwriteInjectableInstance(t *testing.T) { } } +func TestDestroyMatching(t *testing.T) { + _ = di.Inject[greetingService]("abc") + _ = di.Inject[greetingService]("def") + _ = di.Inject[greetingService]("abc_def") + di.DestroyAllMatching(func(key string) bool { return strings.HasPrefix(key, "abc") }) +} + func TestDestroy(t *testing.T) { _ = di.Inject[textService]("a") di.Destroy[textService]("a")