



























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>
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())];
}
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;
}
}
builder.Services.AddInjectionServices();
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。