using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; using System.Text; using System.Threading.Tasks; using Cysharp.Threading.Tasks; namespace BITKit { public class DI { static readonly ConcurrentDictionary dictionary = new(); [ExcuteOnStop] public static void Clear() { //dictionary.Clear(); } public static void Register() where Class : new() { var type = typeof(Interface); lock (dictionary) { if (dictionary.ContainsKey(typeof(Interface))) { BIT4Log.Log($"正在替换{type.Name}为{typeof(Class)}"); } } lock (dictionary) { dictionary.GetOrAdd(typeof(Interface), new Class()); } } public static void Register(Interface c) { lock (dictionary) { dictionary.AddOrUpdate(typeof(Interface), c, (x, y) => c); } } public static void Register(Type t, Type c) { lock (dictionary) dictionary.AddOrUpdate(t, c, (x, y) => Activator.CreateInstance(c)); } public static void Register(Type t, object c) { lock (dictionary) dictionary.AddOrUpdate(t, c, (x, y) => c); } public static T GetOrCreate() where T : new() { lock (dictionary) { var di = dictionary.GetOrAdd(typeof(T), new T()); if (di is T value) { return value; } } throw new Exception(); } public static T GetOrAdd(Func craftFactory) { lock (dictionary) { var di = dictionary.GetOrAdd(typeof(T), craftFactory.Invoke()); if (di is T value) { return value; } } throw new Exception(); } public static T Get() { lock (dictionary) { if (dictionary.TryGetValue(typeof(T), out var obj)) { if (obj is T i) { return i; } } throw new NullReferenceException($"没有找到{typeof(T).Name}"); } } public static async Task GetAsync() { await TaskHelper.WaitUntil(() => dictionary.ContainsKey(typeof(Interface)) && dictionary[typeof(Interface) ]is not null); return Get(); } public static void Inject(object obj) { foreach (var field in obj.GetType().GetFields()) { if (field.GetCustomAttribute() is null && field.GetCustomAttribute() is not null) { lock (dictionary) { if(dictionary!.TryGetValue(field.FieldType,out var value)) { BIT4Log.Log($"已为{obj.GetType().Name}.{field.Name}注入{value.GetType().Name}"); field.SetValue(obj,value); } } } } } } }