依賴注入模式 是做什麼的?
何時使用此技能
在以下情況使用此技能:
- 組織 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 模式請參閱 akka-hosting-actor-patterns 技能。
反模式
不要:在 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 | 無狀態、執行緒安全、建立成本高昂 | 組態、HttpClient 工廠、快取 |
| Scoped | 每個請求有狀態、資料庫內容 | DbContext、儲存庫、使用者內容 |
| Transient | 輕量、有狀態、建立成本低廉 | 驗證器、短期輔助程式 |
// SINGLETON:無狀態服務,可安全共用
services.AddSingleton<IMjmlTemplateRenderer, MjmlTemplateRenderer>();
// SCOPED:資料庫存取,每個請求狀態
services.AddScoped<IUserRepository, UserRepository>();
// TRANSIENT:便宜、短期存在
services.AddTransient<CreateUserRequestValidator>();
Scoped 服務需要一個範圍。 ASP.NET Core 會為每個 HTTP 請求自動建立一個。在背景服務和 Actor 中,請手動建立範圍。
Actor 範圍管理模式請參閱 advanced-patterns.md。
常見錯誤
將 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/zh-tw/dotnet/core/extensions/dependency-injection
- Akka.Hosting:https://github.com/akkadotnet/Akka.Hosting
- Akka.DependencyInjection:https://getakka.net/articles/actors/dependency-injection.html
- Options 模式:請參閱
microsoft-extensions-configuration技能