using System; using System.Collections.Concurrent; using System.Reflection; using System.Threading.Tasks; namespace BITKit { public abstract class InjectFromDI { public T Value { get { return _value ??= DI.Get(); } } private T _value; } public sealed 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 bool TryGet(out T value) { lock (dictionary) { if (dictionary.TryGetValue(typeof(T), out var obj)) { if (obj is T i) { value = i; return true; } } } value = default; return false; } 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 propertyInfo in obj.GetType().GetProperties(ReflectionHelper.Flags)) { try { if (propertyInfo.GetCustomAttribute() is null && propertyInfo.GetCustomAttribute() is not null) { lock (dictionary) { if(dictionary!.TryGetValue(propertyInfo.PropertyType,out var value)) { BIT4Log.Log($"已为{obj.GetType().Name}.{propertyInfo.Name}注入{value.GetType().Name}"); propertyInfo.SetValue(obj,value); } } } } catch (Exception e) { BIT4Log.LogException(e); } } foreach (var field in obj.GetType().GetFields(ReflectionHelper.Flags)) { try { 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); } } } } catch (Exception e) { BIT4Log.LogException(e); } } } } }