This commit is contained in:
CortexCore
2024-03-31 23:31:00 +08:00
parent e179d2eb53
commit b7b89ee71a
641 changed files with 31286 additions and 22134 deletions

View File

@@ -5,7 +5,18 @@ using System.Threading.Tasks;
namespace BITKit
{
public class DI
public abstract class InjectFromDI<T>
{
public T Value
{
get
{
return _value ??= DI.Get<T>();
}
}
private T _value;
}
public sealed class DI
{
static readonly ConcurrentDictionary<Type, object> dictionary = new();
[ExcuteOnStop]
@@ -13,7 +24,7 @@ namespace BITKit
{
//dictionary.Clear();
}
public static void Register<Interface, Class>() where Class : new()
{
var type = typeof(Interface);
@@ -86,28 +97,56 @@ namespace BITKit
throw new NullReferenceException($"没有找到{typeof(T).Name}");
}
}
public static bool TryGet<T>(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<Interface> GetAsync<Interface>()
{
await TaskHelper.WaitUntil(() => dictionary.ContainsKey(typeof(Interface)) && dictionary[typeof(Interface) ]is not null);
return Get<Interface>();
}
/// <summary>
/// 自动依赖注入,将所有带有<see cref="InjectAttribute"/>的字段注入
/// </summary>
/// <param name="obj"></param>
public static void Inject(object obj)
{
foreach (var field in obj.GetType().GetFields())
foreach (var field in obj.GetType().GetFields(ReflectionHelper.Flags))
{
if (field.GetCustomAttribute<ObsoleteAttribute>() is null &&
field.GetCustomAttribute<InjectAttribute>() is not null)
try
{
lock (dictionary)
if (field.GetCustomAttribute<ObsoleteAttribute>() is null &&
field.GetCustomAttribute<InjectAttribute>() is not null)
{
if(dictionary!.TryGetValue(field.FieldType,out var value))
lock (dictionary)
{
BIT4Log.Log<DI>($"已为{obj.GetType().Name}.{field.Name}注入{value.GetType().Name}");
field.SetValue(obj,value);
if(dictionary!.TryGetValue(field.FieldType,out var value))
{
BIT4Log.Log<DI>($"已为{obj.GetType().Name}.{field.Name}注入{value.GetType().Name}");
field.SetValue(obj,value);
}
}
}
}
catch (Exception e)
{
BIT4Log.LogException(e);
}
}
}
}