欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 维修 > C#中的依赖注入

C#中的依赖注入

2025/6/7 9:45:10 来源:https://blog.csdn.net/m0_57417006/article/details/148414113  浏览:    关键词:C#中的依赖注入

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 中广泛使用,支持灵活的服务注册和解析。

           

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词