我知道用这个可以做
services.AddOptions<MyConfigModel>()
.Bind(Configuration.GetSection(nameof(MyConfigModel)))
.ValidateDataAnnotations();
但是我不喜欢通过option.Value.xxx访问。
我更喜欢:
var myconfig = new MyConfigModel();
Configuration.Bind(nameof(MyConfigModel), myconfig);
services.AddSingleton(myconfig);
答案 0 :(得分:2)
为避免由MyConfigModel
解析IOptions<MyConfigModel>.Value
,您可以尝试像
MyConfigModel
services.AddOptions<MyConfigModel>()
.Bind(Configuration.GetSection(nameof(MyConfigModel)))
.ValidateDataAnnotations();
services.AddScoped(serviceProvider => serviceProvider.GetRequiredService<IOptions<MyConfigModel>>().Value);
然后使用
public class HomeController : Controller
{
private readonly MyConfigModel _myConfigModel2;
public HomeController(MyConfigModel myConfigModel)
{
_myConfigModel2 = myConfigModel;
}
}