SuperAPI AI 工具集

dotnet-csharp-dependency-injection

编程与开发

查看项目

更新于 10-16 07:23

技能介绍

用途:为 .NET 应用提供 Microsoft.Extensions.DependencyInjection 的进阶实践,覆盖服务注册与解析、生存期管理、键控服务、装饰、工厂委托、作用域校验和托管服务注册。

主要能力: 服务生存期与捕获依赖:Transient 用 AddTransient<T>() 适合轻量无状态服务;Scoped 用 AddScoped<T>() 适合每请求状态(如 EF Core DbContext);Singleton 用 AddSingleton<T>() 适合线程安全、无状态或共享状态。禁止把短生存期服务注入长生存期服务;单例中应使用 IServiceScopeFactory 创建作用域。 作用域校验:非 Web 主机可用 UseDefaultServiceProvider 设置 ValidateScopes 与 ValidateOnBuild 在启动时校验注册。 注册模式:接口-实现对(AddScoped<IOrderRepository, SqlOrderRepository>())、多实现(IEnumerable<INotifier> 按注册顺序注入)、工厂委托、库代码用 TryAdd 以便应用覆盖。 键控服务(net8.0+):AddKeyedScoped<ICache, RedisCache>("distributed"),通过 [FromKeyedServices("distributed")] 注入或 sp.GetRequiredKeyedService<ICache>("distributed") 手动解析;早期 TFM 需用工厂或字典方案。 装饰:内置容器不原生支持装饰,可手动注册外层实现,或用 Scrutor 的 Decorate。 托管服务:BackgroundService 与 IHostedService 均通过 AddHostedService 注册;它们是单例,必须用 IServiceScopeFactory 创建作用域,不得直接注入 Scoped 服务,ExecuteAsync 内需自行捕获异常(net8.0+ 未处理异常会停止主机)。 组织与测试:用扩展方法分组注册;集成测试可构建 ServiceCollection 与 BuildServiceProvider,单元测试建议直接构造注入与 mock。

限制:键控服务仅 net8.0+ 可用;BackgroundService 的异步模式参考 dotnet-csharp-async-patterns,IOptions 绑定参考 dotnet-csharp-configuration,SOLID/DRY 参考 dotnet-solid-principles,均不在本技能范围。