1. 依赖注入(Dependency Injection, DI)概述
-
定义 :依赖注入是一种设计模式,允许将组件的依赖关系从内部创建转移到外部提供。这样可以降低组件之间的耦合度,提高代码的可测试性、可维护性和可扩展性。
-
核心思想 :类不应该自己创建依赖对象,而应该由外部环境将依赖对象注入到类中。
2. 依赖注入的三种方式
2.1 构造函数注入
-
定义 :依赖通过类的构造函数传递。
-
优点 :强制要求依赖在创建对象时提供,确保对象在使用前已正确初始化。
-
缺点 :如果依赖很多,构造函数参数会变得冗长。
-
示例代码 :
public interface IEmailService { void SendEmail(string to, string subject, string body); } public class SmtpEmailService : IEmailService { public void SendEmail(string to, string subject, string body) { Console.WriteLine($"Sending email via SMTP to {to}: {subject} - {body}"); } } public class CustomerService { private readonly IEmailService _emailService; // 构造函数注入 public CustomerService(IEmailService emailService) { _emailService = emailService; } public void RegisterCustomer(string email) { // 使用注入的依赖 _emailService.SendEmail(email, "Welcome", "Thank you for registering!"); } } // 使用示例 var emailService = new SmtpEmailService(); var customerService = new CustomerService(emailService); customerService.RegisterCustomer("user@example.com");
2.2 属性注入
-
定义 :依赖通过类的属性设置。
-
优点 :可以在对象创建后灵活地注入依赖。
-
缺点 :无法保证依赖在使用前一定被注入,可能导致空引用异常。
示例代码 :
public class CustomerService
{
// 属性注入
public IEmailService EmailService { get; set; }
public void RegisterCustomer(string email)
{
if (EmailService == null)
throw new InvalidOperationException("EmailService not initialized");
EmailService.SendEmail(email, "Welcome", "Thank you for registering!");
}
}
// 使用示例
var customerService = new CustomerService();
customerService.EmailService = new SmtpEmailService(); // 注入依赖
customerService.RegisterCustomer("user@example.com");
2.3 方法注入
-
定义 :依赖通过方法的参数传递。
-
优点 :适用于依赖仅在特定方法中使用的情况。
-
缺点 :每次调用方法都需要传递依赖,可能导致代码冗余。
public class CustomerService { public void RegisterCustomer(string email, IEmailService emailService) // 方法注入 { emailService.SendEmail(email, "Welcome", "Thank you for registering!"); } } // 使用示例 var customerService = new CustomerService(); customerService.RegisterCustomer("user@example.com", new SmtpEmailService());
3. C# 中的依赖注入容器
-
定义 :依赖注入容器是一个管理依赖的对象,负责依赖的注册、解析和生命周期管理。
-
作用 :简化依赖注入的过程,自动创建和管理依赖对象。
3.1 内置依赖注入容器(以 ASP.NET Core 为例)
-
服务注册 :在
Program.cs
文件中使用IServiceCollection
接口注册服务。 -
服务解析 :通过构造函数参数自动解析服务。
using Microsoft.Extensions.DependencyInjection; // 注册服务 var services = new ServiceCollection(); services.AddTransient<IEmailService, SmtpEmailService>(); services.AddTransient<CustomerService>(); // 构建服务提供者 var serviceProvider = services.BuildServiceProvider(); // 解析服务并使用 var customerService = serviceProvider.GetRequiredService<CustomerService>(); customerService.RegisterCustomer("user@example.com");
3.2 自定义依赖注入容器(简单模拟)
-
实现 :使用字典存储接口类型和实现类型的关系,使用
Activator.CreateInstance
创建实例。 -
示例代码 :
using System; using System.Collections.Generic; public class SimpleDIContainer { private readonly Dictionary<Type, Type> _serviceMap = new Dictionary<Type, Type>(); // 注册服务 public void RegisterService<TService, TImplementation>() where TImplementation : TService { _serviceMap[typeof(TService)] = typeof(TImplementation); } // 解析服务 public TService ResolveService<TService>() { if (_serviceMap.TryGetValue(typeof(TService), out var implementationType)) { return (TService)Activator.CreateInstance(implementationType); } else { throw new InvalidOperationException($"No service registered for {typeof(TService).Name}"); } } } // 使用示例 var container = new SimpleDIContainer(); container.RegisterService<IEmailService, SmtpEmailService>(); container.RegisterService<CustomerService, CustomerService>(); var customerService = container.ResolveService<CustomerService>(); customerService.RegisterCustomer("user@example.com");
4. 依赖注入的优势
-
解耦 :组件之间不再直接依赖具体实现,而是依赖抽象接口,降低了耦合度。
-
可测试性 :可以轻松地注入模拟或测试实现,便于单元测试。
-
可扩展性 :可以灵活地替换实现,而无需修改使用组件的代码。
5. 依赖注入的生命周期管理
-
Transient(瞬态) :每次请求都创建一个新的实例。
-
Scoped(作用域) :在请求作用域内共享一个实例(如 HTTP 请求)。
-
Singleton(单例) :整个应用共享一个实例。
-
示例代码 :
using Microsoft.Extensions.DependencyInjection; var services = new ServiceCollection(); // Transient:每次请求都创建新实例 services.AddTransient<IEmailService, SmtpEmailService>(); // Scoped:在作用域内共享实例 services.AddScoped<CustomerService>(); // Singleton:整个应用共享一个实例 services.AddSingleton<IConfigurationService, ConfigurationService>(); var serviceProvider = services.BuildServiceProvider(); // 使用示例 using (var scope = serviceProvider.CreateScope()) { var customerService1 = scope.ServiceProvider.GetRequiredService<CustomerService>(); var customerService2 = scope.ServiceProvider.GetRequiredService<CustomerService>(); // customerService1 和 customerService2 是同一个实例(Scoped) } var configService1 = serviceProvider.GetRequiredService<IConfigurationService>(); var configService2 = serviceProvider.GetRequiredService<IConfigurationService>(); // configService1 和 configService2 是同一个实例(Singleton)
6. 实战场景:日志记录服务
-
场景 :一个日志记录服务,支持多种日志记录方式(如控制台、文件、数据库)。
-
实现 :使用依赖注入来选择不同的日志记录实现。
-
示例代码 :
public interface ILogger { void Log(string message); } public class ConsoleLogger : ILogger { public void Log(string message) { Console.WriteLine($"Console: {message}"); } } public class FileLogger : ILogger { public void Log(string message) { File.AppendAllText("log.txt", $"File: {message}\n"); } } public class LoggerService { private readonly ILogger _logger; public LoggerService(ILogger logger) { _logger = logger; } public void LogMessage(string message) { _logger.Log(message); } } // 使用示例 var services = new ServiceCollection(); services.AddTransient<ILogger, ConsoleLogger>(); // 使用控制台日志 // services.AddTransient<ILogger, FileLogger>(); // 使用文件日志 var serviceProvider = services.BuildServiceProvider(); var loggerService = serviceProvider.GetRequiredService<LoggerService>(); loggerService.LogMessage("This is a log message");
7. 总结
-
依赖注入的核心 :解耦组件之间的依赖关系,提高代码的可测试性和可维护性。
-
主要方式 :构造函数注入、属性注入、方法注入。
-
生命周期管理 :Transient、Scoped、Singleton。
-
实际应用 :在 ASP.NET Core 中广泛使用,支持灵活的服务注册和解析。