配置注入的两种方法, 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 的实例。
浙公网安备 33010602011771号