[C#] #7 依賴注入與介面在C#中的應用 - antqtech/KM GitHub Wiki
依賴注入(Dependency Injection, DI)是一種設計模式,用於實現控制反轉(Inversion of Control, IoC)。它允許將對象的依賴關係在外部進行管理,從而提高程式碼的可測試性和可維護性。在C#中,介面經常用於依賴注入,因為它們提供了一種標準化的方式來定義和實現行為。
依賴注入的基本概念
依賴注入有三種主要方式:
- 構造函數注入:通過構造函數注入依賴。
- 屬性注入:通過屬性注入依賴。
- 方法注入:通過方法參數注入依賴。
範例:電子商務系統中的訂單處理
我們以電子商務系統中的訂單處理為例,展示如何使用依賴注入來管理服務的依賴關係。
1. 定義服務介面
首先,我們定義一個支付服務介面 IPaymentService
和一個通知服務介面 INotificationService
。
public interface IPaymentService
{
void ProcessPayment(decimal amount);
}
public interface INotificationService
{
void NotifyCustomer(string message);
}
2. 實現具體服務
接下來,我們創建兩個具體服務類別,CreditCardPaymentService
和 EmailNotificationService
,它們實現了相應的介面。
public class CreditCardPaymentService : IPaymentService
{
public void ProcessPayment(decimal amount)
{
Console.WriteLine($"Processing credit card payment of {amount}.");
}
}
public class EmailNotificationService : INotificationService
{
public void NotifyCustomer(string message)
{
Console.WriteLine($"Sending email notification: {message}");
}
}
3. 定義訂單處理類別
我們定義一個 OrderProcessor
類別,使用依賴注入來獲取支付服務和通知服務。
public class OrderProcessor
{
private readonly IPaymentService _paymentService;
private readonly INotificationService _notificationService;
// 構造函數注入
public OrderProcessor(IPaymentService paymentService, INotificationService notificationService)
{
_paymentService = paymentService;
_notificationService = notificationService;
}
public void ProcessOrder(decimal amount)
{
_paymentService.ProcessPayment(amount);
_notificationService.NotifyCustomer("Your order has been processed.");
}
}
4. 使用依賴注入容器
在現代C#應用程式中,通常使用依賴注入容器來管理依賴關係。在這個範例中,我們使用內建的依賴注入容器來配置和解析依賴。
using Microsoft.Extensions.DependencyInjection;
class Program
{
static void Main(string[] args)
{
// 建立服務集合
var serviceCollection = new ServiceCollection();
// 註冊服務
serviceCollection.AddTransient<IPaymentService, CreditCardPaymentService>();
serviceCollection.AddTransient<INotificationService, EmailNotificationService>();
serviceCollection.AddTransient<OrderProcessor>();
// 建立服務提供者
var serviceProvider = serviceCollection.BuildServiceProvider();
// 解析並使用 OrderProcessor
var orderProcessor = serviceProvider.GetService<OrderProcessor>();
orderProcessor.ProcessOrder(100.0m);
}
}
在這裡,我們使用 ServiceCollection
來註冊服務,並使用 BuildServiceProvider
來建立服務提供者。然後,我們可以使用 GetService
方法來解析 OrderProcessor
並處理訂單。
優點與應用
優點
- 提高可測試性:依賴注入使得我們可以輕鬆地使用模擬(mock)對象進行單元測試。
- 降低耦合度:依賴注入使得類別之間的依賴關係更加鬆散,從而提高了系統的可維護性。
- 提高靈活性:可以根據需要輕鬆替換具體實現,而不需要修改客戶端程式碼。
應用場景
依賴注入適合用於以下情況:
- 需要管理複雜依賴關係:例如大型應用程式中的服務和存儲庫(repository)層。
- 需要進行單元測試:依賴注入使得我們可以輕鬆地替換具體實現,以進行單元測試。
- 需要靈活配置:可以根據不同的環境或配置使用不同的實現。
總結
依賴注入是一種強大的設計模式,通過將對象的依賴關係在外部進行管理,提供了一種靈活且可測試的方式來構建應用程式。介面在依賴注入中扮演關鍵角色,提供了統一的契約,確保不同的實現具有一致的行為。通過理解和應用依賴注入,我們可以更有效地管理應用程式的依賴關係,提高程式碼的靈活性和可維護性。