在现代 C# 开发中,依赖注入(Dependency Injection, DI)和工厂模式(Factory Pattern)是两种非常重要的设计思想。它们各自解决不同的问题,但当二者结合时,能带来更灵活、可测试、可维护的代码结构。本文将手把手教你如何在 C# 中通过依赖注入的工厂模式扩展来构建高内聚、低耦合的应用程序。
依赖注入是一种控制反转(IoC)的实现方式,它允许我们将对象的依赖关系从内部创建转移到外部提供。这样做的好处是:
工厂模式是一种创建型设计模式,它封装了对象的创建逻辑。当你需要根据运行时条件动态创建不同类型的对象时,工厂模式就派上用场了。
有时,我们无法在应用启动时就确定要使用哪个具体实现(比如根据用户输入、配置文件或数据库状态),这时就需要在运行时动态创建服务实例。如果直接在业务逻辑中 new 对象,会破坏依赖注入原则。因此,我们需要一个“可注入的工厂”——这就是C#依赖注入工厂扩展的核心思想。
假设我们有一个支付系统,支持支付宝和微信支付。我们希望根据用户选择的支付方式动态创建对应的支付服务。
public interface IPaymentService{ Task ProcessPaymentAsync(decimal amount);}public class AlipayService : IPaymentService{ public async Task<bool> ProcessPaymentAsync(decimal amount) { // 模拟支付宝支付逻辑 Console.WriteLine($"Alipay processing {amount}..."); return await Task.FromResult(true); }}public class WechatPayService : IPaymentService{ public async Task<bool> ProcessPaymentAsync(decimal amount) { // 模拟微信支付逻辑 Console.WriteLine($"WeChat Pay processing {amount}..."); return await Task.FromResult(true); }} public enum PaymentType{ Alipay, WechatPay}public interface IPaymentServiceFactory{ IPaymentService Create(PaymentType type);}public class PaymentServiceFactory : IPaymentServiceFactory{ private readonly IServiceProvider _serviceProvider; public PaymentServiceFactory(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public IPaymentService Create(PaymentType type) { return type switch { PaymentType.Alipay => _serviceProvider.GetRequiredService<AlipayService>(), PaymentType.WechatPay => _serviceProvider.GetRequiredService<WechatPayService>(), _ => throw new ArgumentException("Unsupported payment type") }; }} // .NET 6+ 的 Program.csvar builder = WebApplication.CreateBuilder(args);// 注册具体实现builder.Services.AddScoped<AlipayService>();builder.Services.AddScoped<WechatPayService>();// 注册工厂builder.Services.AddScoped<IPaymentServiceFactory, PaymentServiceFactory>();var app = builder.Build();// ... 其他配置 [ApiController][Route("[controller]")]public class PaymentController : ControllerBase{ private readonly IPaymentServiceFactory _factory; public PaymentController(IPaymentServiceFactory factory) { _factory = factory; } [HttpPost("process")] public async Task<IActionResult> ProcessPayment([FromBody] PaymentRequest request) { var service = _factory.Create(request.Type); var success = await service.ProcessPaymentAsync(request.Amount); return Ok(new { Success = success }); }}public class PaymentRequest{ public PaymentType Type { get; set; } public decimal Amount { get; set; }} 如果你有多个类似的场景,可以创建一个通用的泛型工厂,避免重复代码:
public interface IGenericFactory<TKey, TService>{ TService Create(TKey key);}// 实现略,可根据 Dictionary 或策略模式扩展 通过将工厂模式与C#依赖注入结合,我们既能保持代码的松耦合,又能灵活地在运行时创建所需的服务实例。这种依赖注入工厂扩展的方式,是构建大型、可维护 C# 应用的重要技巧。
无论你是刚接触 C# 设计模式的新手,还是希望优化现有架构的开发者,掌握这一组合都能显著提升你的代码质量。
关键词回顾:C#依赖注入、工厂模式、C#设计模式、依赖注入工厂扩展。
本文由主机测评网于2025-12-10发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://vpshk.cn/2025125927.html