怪奇物语

怪奇物语

首页 新随笔 联系 管理

配置注入的两种方法, Settings, appsettings.json,依赖注入

1. AddSingleton(configurationRoot.GetSection(FTPSettings.Key).Get<FTPSettings>())

  • 作用:直接将 FTPSettings 的实例注册为单例。

  • 用法:通过构造函数注入 FTPSettings,类型为 FTPSettings

  • 示例

    public class MyService
    {
        private readonly FTPSettings _ftpSettings;
        public MyService(FTPSettings ftpSettings)
        {
            _ftpSettings = ftpSettings;
        }
    }
    

2. Configure<FTPSettings>(configurationRoot.GetSection(FTPSettings.Key))

  • 作用:使用 IOptions<FTPSettings>IOptionsSnapshot<FTPSettings> 机制注册配置,支持配置变更和绑定。

  • 用法:通过构造函数注入 IOptions<FTPSettings>IOptionsSnapshot<FTPSettings>,再通过 .Value 获取实例。

  • 示例

    using Microsoft.Extensions.Options;
    
    public class MyService
    {
        private readonly FTPSettings _ftpSettings;
        public MyService(IOptions<FTPSettings> options)
        {
            _ftpSettings = options.Value;
        }
    }
    

总结

  • 直接注册实例:简单,适合配置不会变更的场景。
  • 使用 Configure:推荐,支持配置变更、依赖注入生态更好。

建议:优先使用 Configure + IOptions<T> 方式。
如果两种方式都注册,注入 FTPSettings 时会得到直接注册的实例,注入 IOptions<FTPSettings> 时会得到 Configure 的实例。

posted on 2025-07-05 08:00  超级无敌美少男战士  阅读(20)  评论(0)    收藏  举报