注:该写法仅适用于 .NET 8 及以上
public static class ServiceCollectionExtensions
{public static void AddServices<TBase>(this IServiceCollection services, ServiceLifetime lifetime = ServiceLifetime.Transient, Assembly? assembly = null){assembly ??= typeof(TBase).Assembly;var types = assembly.GetTypes().Where(t => typeof(TBase).IsAssignableFrom(t) && t.IsClass && !t.IsAbstract).ToList();foreach (var type in types){string? key = type.FullName;if (string.IsNullOrWhiteSpace(key)){continue;}switch (lifetime){case ServiceLifetime.Scoped:services.AddScoped(typeof(TBase), type);break;case ServiceLifetime.Singleton:services.AddSingleton(typeof(TBase), type);break;case ServiceLifetime.Transient:default:services.AddTransient(typeof(TBase), type);break;}}}
}
// 很适合策略模式~builder.Services.AddServices<AStrategy>(ServiceLifetime.Transient);
builder.Services.AddServices<BStrategy>(ServiceLifetime.Transient);
builder.Services.AddServices<CStrategy>(ServiceLifetime.Transient);