Files
mayfly-go/server/pkg/ioc/default.go
2026-04-15 12:47:10 +08:00

50 lines
1.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package ioc
import (
"mayfly-go/pkg/utils/collx"
"mayfly-go/pkg/utils/structx"
"reflect"
)
// 全局默认实例容器
var DefaultContainer = NewContainer()
// 注册实例至全局默认ioc容器
func Register(component any, opts ...ComponentOption) {
DefaultContainer.Register(component, opts...)
}
// RegisterByType 根据组件实例类型注册至全局默认ioc容器会自动创建实例
func RegisterByType[T any](opts ...ComponentOption) {
DefaultContainer.Register(structx.NewInstance[T](), opts...)
}
// Get 根据组件实例类型从全局默认ioc容器获取实例
func Get[T any]() T {
c, _ := DefaultContainer.GetByType(reflect.TypeOf((*T)(nil)).Elem())
return c.(T)
}
// GetByName 根据组件名从全局默认ioc容器获取实例
func GetByName[T any](name string) T {
c, _ := DefaultContainer.Get(name)
return c.(T)
}
// GetBeansByType 根据组件实例类型从全局默认ioc容器获取实例
func GetBeansByType[T any]() []T {
return collx.ArrayMap(DefaultContainer.GetBeansByType(reflect.TypeOf((*T)(nil)).Elem()), func(val any) T {
return val.(T)
})
}
// Inject 使用全局默认ioc容器中已注册的组件实例 -> 注入到指定实例所依赖的组件实例
func Inject(component any) error {
return DefaultContainer.Inject(component)
}
// InjectComponents 注入默认ioc容器内组件所依赖的其他组件实例
func InjectComponents() error {
return DefaultContainer.InjectComponents()
}