依赖注入模式 是做什么的?
何时使用此技能
在以下情况下使用此技能:
- 组织 ASP.NET Core 应用程序中的服务注册
- 避免拥有数百行注册代码的庞大 Program.cs/Startup.cs 文件
- 使服务配置在生产环境和测试之间可重用
- 设计集成 Microsoft.Extensions.DependencyInjection 的库
参考文件
- advanced-patterns.md: 使用 DI 扩展进行测试、Akka.NET actor 作用域管理、条件/工厂/键控注册模式
问题所在
没有组织,Program.cs 将变得难以管理:
// 糟糕:200 多行混乱的注册代码
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddScoped<IOrderRepository, OrderRepository>();
builder.Services.AddScoped<IProductRepository, ProductRepository>();
builder.Services.AddScoped<IUserService, UserService>();
// ... 还有 150 多行 ...
问题:难以找到相关注册,没有清晰的边界,无法在测试中重用,存在合并冲突。
解决方案:扩展方法组合
将相关注册分组到扩展方法中:
// 良好:干净、可组合的 Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddUserServices()
.AddOrderServices()
.AddEmailServices()
.AddPaymentServices()
.AddValidators();
var app = builder.Build();
扩展方法模式
基本结构
namespace MyApp.Users;
public static class UserServiceCollectionExtensions
{
public static IServiceCollection AddUserServices(this IServiceCollection services)
{
services.AddScoped<IUserRepository, UserRepository>();
services.AddScoped<IUserReadStore, UserReadStore>();
services.AddScoped<IUserWriteStore, UserWriteStore>();
services.AddScoped<IUserService, UserService>();
services.AddScoped<IUserValidationService, UserValidationService>();
return services;
}
}
带配置
namespace MyApp.Email;
public static class EmailServiceCollectionExtensions
{
public static IServiceCollection AddEmailServices(
this IServiceCollection services,
string configSectionName = "EmailSettings")
{
services.AddOptions<EmailOptions>()
.BindConfiguration(configSectionName)
.ValidateDataAnnotations()
.ValidateOnStart();
services.AddSingleton<IMjmlTemplateRenderer, MjmlTemplateRenderer>();
services.AddSingleton<IEmailLinkGenerator, EmailLinkGenerator>();
services.AddScoped<IUserEmailComposer, UserEmailComposer>();
services.AddScoped<IEmailSender, SmtpEmailSender>();
return services;
}
}
文件组织
将扩展方法放在它们所注册的服务附近:
src/
MyApp.Api/
Program.cs # 组合所有 Add* 方法
MyApp.Users/
Services/
UserService.cs
UserServiceCollectionExtensions.cs # AddUserServices()
MyApp.Orders/
OrderServiceCollectionExtensions.cs # AddOrderServices()
MyApp.Email/
EmailServiceCollectionExtensions.cs # AddEmailServices()
惯例:将 {Feature}ServiceCollectionExtensions.cs 放在该功能的服务旁边。
命名约定
| 模式 | 用途 |
|---|---|
Add{Feature}Services() | 通用功能注册 |
Add{Feature}() | 不引起歧义时的简短形式 |
Configure{Feature}() | 主要用于设置选项时 |
Use{Feature}() | 中间件(用于 IApplicationBuilder) |
测试优势
Add* 模式让你可以在测试中重用生产配置,并且只覆盖不同的部分。适用于 WebApplicationFactory、Akka.Hosting.TestKit 和独立的 ServiceCollection。
请参阅 advanced-patterns.md 获取完整的测试示例。
分层扩展
对于大型应用程序,可以分层组合扩展:
public static class AppServiceCollectionExtensions
{
public static IServiceCollection AddAppServices(this IServiceCollection services)
{
return services
.AddDomainServices()
.AddInfrastructureServices()
.AddApiServices();
}
}
public static class DomainServiceCollectionExtensions
{
public static IServiceCollection AddDomainServices(this IServiceCollection services)
{
return services
.AddUserServices()
.AddOrderServices()
.AddProductServices();
}
}
Akka.Hosting 集成
相同的模式也适用于 Akka.NET actor 配置:
public static class OrderActorExtensions
{
public static AkkaConfigurationBuilder AddOrderActors(
this AkkaConfigurationBuilder builder)
{
return builder
.WithActors((system, registry, resolver) =>
{
var orderProps = resolver.Props<OrderActor>();
var orderRef = system.ActorOf(orderProps, "orders");
registry.Register<OrderActor>(orderRef);
});
}
}
// 在 Program.cs 中使用
builder.Services.AddAkka("MySystem", (builder, sp) =>
{
builder
.AddOrderActors()
.AddInventoryActors()
.AddNotificationActors();
});
请参阅 akka-hosting-actor-patterns 技能了解完整的 Akka.Hosting 模式。
反模式
不要:将所有注册都放在 Program.cs 中
// 糟糕:包含 200+ 行注册代码的庞大 Program.cs
不要:创建过于通用的扩展
// 糟糕:过于模糊,无法传达注册了什么
public static IServiceCollection AddServices(this IServiceCollection services) { ... }
不要:隐藏重要配置
// 糟糕:埋藏起来的设置
public static IServiceCollection AddDatabase(this IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer("hardcoded-connection-string")); // 隐藏了!
}
// 良好:明确接受配置
public static IServiceCollection AddDatabase(
this IServiceCollection services,
string connectionString)
{
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(connectionString));
}
最佳实践总结
| 实践 | 优势 |
|---|---|
将相关服务分组到 Add* 方法中 | 清晰的 Program.cs,明确的边界 |
| 将扩展放在其注册的服务附近 | 易于查找和维护 |
返回 IServiceCollection 以支持链式调用 | 流式 API |
| 接受配置参数 | 灵活性 |
使用一致的命名(Add{Feature}Services) | 可发现性 |
| 通过重用生产扩展进行测试 | 信心增强,减少重复 |
生命周期管理
| 生命周期 | 使用场景 | 示例 |
|---|---|---|
| Singleton | 无状态、线程安全、创建成本高 | Configuration、HttpClient 工厂、缓存 |
| Scoped | 每个请求有状态、数据库上下文 | DbContext、存储库、用户上下文 |
| Transient | 轻量级、有状态、创建成本低 | 验证器、短期助手 |
// SINGLETON:无状态服务,可以安全共享
services.AddSingleton<IMjmlTemplateRenderer, MjmlTemplateRenderer>();
// SCOPED:数据库访问,每个请求状态
services.AddScoped<IUserRepository, UserRepository>();
// TRANSIENT:廉价、短期
services.AddTransient<CreateUserRequestValidator>();
Scoped 服务需要作用域。 ASP.NET Core 会为每个 HTTP 请求创建一个作用域。在后台服务和 actor 中,需要手动创建作用域。
请参阅 advanced-patterns.md 了解 actor 作用域管理模式。
常见错误
将 Scoped 注入到 Singleton 中
// 糟糕:Singleton 捕获了 scoped 服务 - DbContext 会失效!
public class CacheService // 注册为 Singleton
{
private readonly IUserRepository _repo; // Scoped - 在启动时捕获!
}
// 良好:注入 IServiceProvider,每次操作创建作用域
public class CacheService
{
private readonly IServiceProvider _serviceProvider;
public async Task<User> GetUserAsync(string id)
{
using var scope = _serviceProvider.CreateScope();
var repo = scope.ServiceProvider.GetRequiredService<IUserRepository>();
return await repo.GetByIdAsync(id);
}
}
后台工作没有作用域
// 糟糕:scoped 服务没有作用域
public class BadBackgroundService : BackgroundService
{
private readonly IOrderService _orderService; // Scoped - 会抛出异常!
}
// 良好:为每个工作单元创建作用域
public class GoodBackgroundService : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
protected override async Task ExecuteAsync(CancellationToken ct)
{
using var scope = _scopeFactory.CreateScope();
var orderService = scope.ServiceProvider.GetRequiredService<IOrderService>();
// ...
}
}
资源
- Microsoft.Extensions.DependencyInjection: https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection
- Akka.Hosting: https://github.com/akkadotnet/Akka.Hosting
- Akka.DependencyInjection: https://getakka.net/articles/actors/dependency-injection.html
- 选项模式: 请参阅
microsoft-extensions-configuration技能