BITFALL/Assets/BITKit/Core/DependencyInjection/DependencyInjection.cs

116 lines
3.5 KiB
C#

using System;
using System.Collections.Concurrent;
using System.Reflection;
using System.Threading.Tasks;
namespace BITKit
{
public class DI
{
static readonly ConcurrentDictionary<Type, object> dictionary = new();
[ExcuteOnStop]
public static void Clear()
{
//dictionary.Clear();
}
public static void Register<Interface, Class>() where Class : new()
{
var type = typeof(Interface);
lock (dictionary)
{
if (dictionary.ContainsKey(typeof(Interface)))
{
BIT4Log.Log<DI>($"正在替换{type.Name}为{typeof(Class)}");
}
}
lock (dictionary)
{
dictionary.GetOrAdd(typeof(Interface), new Class());
}
}
public static void Register<Interface>(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<T>() 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<T>(Func<T> 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<T>()
{
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<Interface> GetAsync<Interface>()
{
await TaskHelper.WaitUntil(() => dictionary.ContainsKey(typeof(Interface)) && dictionary[typeof(Interface) ]is not null);
return Get<Interface>();
}
public static void Inject(object obj)
{
foreach (var field in obj.GetType().GetFields())
{
if (field.GetCustomAttribute<ObsoleteAttribute>() is null &&
field.GetCustomAttribute<InjectAttribute>() is not null)
{
lock (dictionary)
{
if(dictionary!.TryGetValue(field.FieldType,out var value))
{
BIT4Log.Log<DI>($"已为{obj.GetType().Name}.{field.Name}注入{value.GetType().Name}");
field.SetValue(obj,value);
}
}
}
}
}
}
}