[英]Use System.Uri in strongly typed configuration class for ASP.net core app
In our AspNetCore 2.2
app, we make use of strongly typed classes for configuration sections, following the pattern:在我们的AspNetCore 2.2
应用程序中,我们对配置部分使用强类型类,遵循以下模式:
public static IServiceCollection AddMyConfigSettings(this IServiceCollection services, IConfiguration configuration)
{
MyConfigSettings myConfigSettings = new MyConfigSettings();
configuration.Bind("MyConfig", myConfigSettings);
services.AddSingleton(myConfigSettings);
return services;
}
Now the MyConfigSettings
class looks like this:现在MyConfigSettings
类看起来像这样:
public class MyConfigSettings
{
#pragma warning disable CA1056 // Uri properties should not be strings
public string HostUrl { get; set; }
}
Is there an easy way to use System.Uri
instead of System.String
as type for HostUrl, so that we don't need to suppress the Roslyn analyzer warning CA1056 ?有没有一种简单的方法可以使用System.Uri
而不是System.String
作为 HostUrl 的类型,这样我们就不需要抑制 Roslyn 分析器警告CA1056 ?
Change the property from string
to Uri
.将属性从string
更改为Uri
。
public class MyConfigSettings {
public Uri HostUrl { get; set; }
}
The bind should take care of the rest.绑定应该处理其余的。
You can also bind to the object graph like this您还可以像这样绑定到对象图
public static IServiceCollection AddMyConfigSettings(this IServiceCollection services, IConfiguration configuration) {
MyConfigSettings myConfigSettings = configuration.GetSection("MyConfig").Get<MyConfigSettings>();
services.AddSingleton(myConfigSettings);
return services;
}
ConfigurationBinder.Get<T>
binds and returns the specified type.ConfigurationBinder.Get<T>
绑定并返回指定的类型。Get<T>
is more convenient than usingBind
.Get<T>
比使用Bind
更方便。
The preceeding code shows how to use Get<T>
with the your example, which allows the bound instance to be directly assigned to the property.前面的代码显示了如何在您的示例中使用Get<T>
,这允许将绑定实例直接分配给属性。
Reference Configuration in ASP.NET Core: Bind to an object graph ASP.NET Core 中的参考配置:绑定到对象图
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.