静态类中的Asp.Net Core配置

问题描述 投票:0回答:2

我想在静态类中读取appsettings.json文件中的url.我尝试了一些东西,如

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

但每当我想打电话 GetSection() 方法,我得到的是空值。

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

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

c# asp.net-core configuration
2个回答
2
投票

正如它提到的 此处你可以将静态属性添加到你的 Startup.cs

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
    StaticConfig = configuration;
}

public static IConfiguration StaticConfig { get; private set; }

并在静态类中使用。

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


1
投票

The ConfigurationManager api在ASP.NET core中的工作方式并不像你期望的那样,它不会抛出任何异常,而只是简单地返回了 null 每当你调用它的方法时,就像你正在经历的那样。

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

你缺少的另一块是你在ASP.NET core中的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);
  }
}

-1
投票

使用...

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

更新:抱歉,这是基于这样的假设,即配置已经被注入到了

© www.soinside.com 2019 - 2024. All rights reserved.