【自动注入】.NET8/.NETCore 依赖注入:自动注入项目中所有接口和自定义类
参考
https://blog.csdn.net/jonnysun/article/details/144201359
创建工具类库
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.0" />
</ItemGroup>
</Project>
IDependency接口
public interface IDependency { }
public interface ITransientDependency : IDependency { }
public interface IScopedDependency : IDependency { }
public interface ISingletonDependency : IDependency { }
全局程序集
public static class GlobalAssemblies
{
public static readonly Assembly[] AllAssemblies =
[
Assembly.Load("Keep.Application"),
];
public static readonly Type[] AllTypes = [.. AllAssemblies.SelectMany(x => x.GetTypes())];
}
HostExtensions扩展方法
public static class HostExtensions
{
public static IServiceCollection AddInjectionServices(this IServiceCollection services)
{
Dictionary<Type, ServiceLifetime> lifeTimeMap = new()
{
{ typeof(ITransientDependency),ServiceLifetime.Transient },
{ typeof(IScopedDependency),ServiceLifetime.Scoped },
{ typeof(ISingletonDependency),ServiceLifetime.Singleton },
{ typeof(IDependency),ServiceLifetime.Scoped },
};
var typeList = GlobalAssemblies.AllTypes;
foreach (var type in typeList)
{
foreach (var map in lifeTimeMap)
{
var interfaceDependency = map.Key;
if ((interfaceDependency.IsAssignableFrom(type) && interfaceDependency != type && !type.IsAbstract && type.IsClass) == false)
continue;
bool hasInterafce = false;
foreach (var @inteface in typeList.Where(x => x.IsInterface && x.IsAssignableFrom(type) && x != interfaceDependency))
{
services.Add(new ServiceDescriptor(@inteface, type, map.Value));
hasInterafce = true;
}
if (hasInterafce == false)
services.Add(new ServiceDescriptor(type, type, map.Value));
}
}
return services;
}
}
使用Program.cs
builder.Services.AddInjectionServices();

浙公网安备 33010602011771号