静态类中的Asp.Net核心配置



我想从静态类中的appsettings.json文件中读取url。我试过类似的东西

private static string Url => ConfigurationManager.GetSection("Urls/SampleUrl").ToString();

但每当我尝试调用GetSection()方法时,我都会得到null值。

"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ConnectionStrings": {
"cs1": "some string",
"cs2": "other string"
},
"Urls": {
"SampleUrl": "google.com"
},
"AllowedHosts": "*"

我只是想从appsettings中读取一些数据。根据文档,我不应该以某种方式注册我的standart appsettings.json文件,因为程序类中的Host.CreateDefaultBuilder(args)默认为我注册。

如前所述,您可以将静态属性添加到Startup.cs

public Startup(IConfiguration configuration)
{
Configuration = configuration;
StaticConfig = configuration;
}
public static IConfiguration StaticConfig { get; private set; }

并用于静态类:

var x = Startup.StaticConfig.GetSection("whatever");

ConfigurationManagerapi在ASP.NET核心中的工作方式与预期不同。它不会抛出任何异常,但只要您调用它的方法,它就会返回null,正如您所经历的那样。

在ASP.NET核心中,您有新的对象和API来将配置传递给应用程序。它们基于配置源的思想,配置源可以在配置生成器中注册,一旦构建完成,就会为您提供配置对象。如果使用默认的主机生成器,则会自动考虑appsettings.json文件的配置源,因此您可以开箱即用。此处提供完整的文档。

您缺少的另一部分是ASP.NET核心中的DI容器。该框架非常有主见,并引导您进行基于依赖注入模式的设计。每当您的服务需要某个东西时,他们只需通过构造函数参数请求它,而其他参与者(DI容器(将负责解决依赖关系并注入请求的对象。在DI容器中自动注册的接口之一是IConfiguration接口,它基本上是您传递给应用程序的配置。

也就是说,在我看来,你的设计是不正确的从静态类访问应用程序配置是没有意义的。静态类通常是静态方法的容器,静态方法基本上是接收输入并产生输出的函数。把它们看作是为您实现计算的纯函数,可以用作解决特定问题的助手。举个例子,考虑以下静态类:

public static class StringHelpers 
{
// notice that this is a pure function. This code does not know it is running inside an application having some sort of injected configuration. This is only an helper function
public static string Normalize(string str)
{
if (str is null)
{
throw new ArgumentNullException(nameof(str));
}
return str.Trim().ToUpperInvariant();
}
}

完全有可能您的静态方法需要您的一些配置作为输入才能工作。在这种情况下,您应该选择以下设计:

public interface IUrlProvider 
{
string GetUrl();
}
public class ConfigurationBasedUrlProvider: IUrlProvider
{
private const string DefaultUrl = "https://foo.example.com/foo/bar";
private readonly IConfiguration _appConfiguration;
// ask the DI container to inject the configuration. Here you have the content of appsettings.json for free. Interface IConfiguration is automatically registered with the DI container
public ConfigurationBasedUrlProvider(IConfiguration configuration)
{
_appConfiguration = configuration ?? throw new ArgumentNullException(nameof(configuration));
}
public string GetUrl()
{
var configuredUrl = _appConfiguration.GetSection("Urls")["SampleUrl"];
var safeUrl = string.IsNullOrWhiteSpace(configuredUrl) ? DefaultUrl : configuredUrl;
return StringHelpers.Normalize(safeUrl);
}
}

使用。。。

Configuration.GetSection("Urls").GetValue<string>("SampleUrl");

更新:对不起,这是基于这样的假设,即配置已经注入

最新更新