add delete match function

This commit is contained in:
admin 2025-08-30 21:43:36 +02:00
parent d5fcd40f50
commit 4f04dc57d8
3 changed files with 25 additions and 1 deletions

View File

@ -84,8 +84,20 @@ func (c *container) destroy(typ reflect.Type, identifier ...string) {
delete(c.instances, instanceSelector) 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 { func (c *container) getSelector(typ reflect.Type, identifier ...string) string {
typeName := typ.String() typeName := typ.String()
additionalKey := strings.Join(identifier, "_") additionalKey := strings.Join(identifier, "_")
return fmt.Sprintf("%s_%s", typeName, additionalKey) return fmt.Sprintf("%s_%s", additionalKey, typeName)
} }

View File

@ -35,3 +35,7 @@ func Destroy[T any](identifier ...string) {
typ := reflect.TypeOf((*T)(nil)).Elem() typ := reflect.TypeOf((*T)(nil)).Elem()
getContainer().destroy(typ, identifier...) getContainer().destroy(typ, identifier...)
} }
func DestroyAllMatching(match func(string) bool) {
getContainer().destroyAllMatching(match)
}

View File

@ -2,6 +2,7 @@ package di_test
import ( import (
"fmt" "fmt"
"strings"
"testing" "testing"
di "git.apihub24.de/admin/generic-di" 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) { func TestDestroy(t *testing.T) {
_ = di.Inject[textService]("a") _ = di.Inject[textService]("a")
di.Destroy[textService]("a") di.Destroy[textService]("a")