add delete match function
This commit is contained in:
parent
d5fcd40f50
commit
4f04dc57d8
14
container.go
14
container.go
@ -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)
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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)
|
||||||
|
}
|
||||||
|
|||||||
@ -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")
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user