第六章 依赖注入和服务配置

6.1 依赖注入基础

什么是依赖注入

依赖注入(Dependency Injection,简称DI)是一种设计模式,它允许对象及其依赖项之间的松散耦合。在依赖注入模式中,对象不直接创建其依赖项,而是从外部接收已创建的依赖项实例。

依赖注入的核心原则:

  • 依赖反转原则:高层模块不应依赖低层模块,两者都应依赖抽象
  • 控制反转:控制流的反转,对象的创建和生命周期由外部容器管理
  • 显式依赖:类应明确声明其所有依赖项

6.2 服务生命周期

ASP.NET Core DI容器支持三种主要的服务生命周期:

Transient(瞬态)

  • 定义:每次请求服务时创建新实例
  • 注册方式services.AddTransient<IService, Service>()
  • 适用场景:轻量级、无状态服务

Scoped(作用域)

  • 定义:每个请求(HTTP请求)内共享同一实例
  • 注册方式services.AddScoped<IService, Service>()
  • 适用场景:需要保持请求内状态的服务,如数据库上下文

Singleton(单例)

  • 定义:应用程序生命周期内只创建一个实例
  • 注册方式services.AddSingleton<IService, Service>()
  • 适用场景:无状态服务、共享缓存、配置服务

6.3 选项模式 (Options Pattern)

基本用法

使用选项模式的基本步骤:

  1. 创建选项类:

    public class SmtpSettings
    {
    public const string SectionName = "Smtp";

    复制代码
     public string Server { get; set; } = string.Empty;
     public int Port { get; set; } = 25;
     public string Username { get; set; } = string.Empty;
     public string Password { get; set; } = string.Empty;
     public bool EnableSsl { get; set; } = true;
     public string FromEmail { get; set; } = string.Empty;
     public string FromName { get; set; } = string.Empty;

    }

  2. 配置选项:

    // 在Program.cs中
    builder.Services.Configure<SmtpSettings>(
    builder.Configuration.GetSection(SmtpSettings.SectionName));

  3. 在appsettings.json中添加配置:

    {
    "Smtp": {
    "Server": "smtp.example.com",
    "Port": 587,
    "Username": "user@example.com",
    "Password": "SecurePassword123",
    "EnableSsl": true,
    "FromEmail": "no-reply@example.com",
    "FromName": "My Application"
    }
    }

  4. 使用选项:

    public class EmailService : IEmailService
    {
    private readonly SmtpSettings _smtpSettings;

    复制代码
     public EmailService(IOptions<SmtpSettings> smtpOptions)
     {
         _smtpSettings = smtpOptions.Value;
     }
    
     // 使用配置进行邮件发送

    }