简体   繁体   English

static class 中的 Asp.Net Core 配置

[英]Asp.Net Core configuration in static class

I want to read url from my appsettings.json file within static class.我想从我的 appsettings.json 文件中读取 url static ZA2F2ED4F8EBC2CBB4C21A29 I tried something like我尝试了类似的东西

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

But whenever i try to call GetSection() method i get null value.但是每当我尝试调用GetSection()方法时,我都会得到 null 值。

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

I simply want to read some data from appsettings.我只是想从 appsettings 中读取一些数据。 According to docs i should not somehow register my standart appsettings.json file because Host.CreateDefaultBuilder(args) in Program class does it for me by default.根据文档,我不应该以某种方式注册我的标准 appsettings.json 文件,因为程序 class 中的Host.CreateDefaultBuilder(args)默认为我执行此操作。

As it mentioned here , you can add static property to your Startup.cs正如这里提到的,您可以将 static 属性添加到您的Startup.cs

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

public static IConfiguration StaticConfig { get; private set; }

And use in static class:并在 static class 中使用:

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

The ConfigurationManager api does not work the way you expect it to in ASP.NET core. ConfigurationManager api 无法按照您在 ASP.NET 内核中的预期方式工作。 It won't throw any exception, but simply returns null whenever you call its methods, as you are experiencing.它不会抛出任何异常,而是在您调用它的方法时简单地返回null ,就像您遇到的那样。

In ASP.NET core you have new objects and APIs to pass configuration to your application.在 ASP.NET 内核中,您有新的对象和 API 可以将配置传递给您的应用程序。 They are based around the idea of configuration sources which can be registered with a configuration builder which, once builded, gives you the configuration object.它们基于配置源的想法,可以使用配置构建器注册,一旦构建,配置构建器就会为您提供配置 object。 The configuration source for the appsettings.json file is automatically taken into account if you use the default host builder, so you have it out of the box.如果您使用默认主机构建器,则会自动考虑appsettings.json文件的配置源,因此您可以直接使用它。 Full documentation is available here .完整的文档可在此处获得。

The other piece you are missing is the DI container that you have in ASP.NET core.您缺少的另一部分是 ASP.NET 内核中的 DI 容器。 The framework is strongly opinionated and guides you to a design based on the dependency injection pattern.该框架具有强烈的固执己见,并指导您基于依赖注入模式进行设计。 Each time your services need something they simply ask for it via a constructor parameter and some other actor (the DI container) will take care of resolving the dependency and to inject the requested object.每次您的服务需要某些东西时,他们只需通过构造函数参数请求它,而其他一些参与者(DI 容器)将负责解决依赖关系并注入请求的 object。 One of the interfaces that are automatically registered in the DI container is the IConfiguration interface, which is basically the configuration that you have passed to your application.在 DI 容器中自动注册的接口之一是IConfiguration接口,它基本上是您传递给应用程序的配置。

That said in my opinion your design is not correct.这在我看来你的设计是不正确的。 Accessing the application configuration from a static class does not make sense .从 static class 访问应用程序配置没有意义 Static classes are usually meant to be the container of static methods, which are basically functions receiveing an input and producing an output. Static 类通常是 static 方法的容器,这些方法基本上是接收输入并产生 output 的函数。 Think of them as pure functions which implements calculations for you and can be used as helpers to solve a particular problem.将它们视为为您实现计算的纯函数,并可用作解决特定问题的助手。 Just to give you an example, consider the following static class:举个例子,考虑下面的 static class:

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();
  }
}

It is entirely possible that your static methods needs some of your configuration as an input in order to work.您的 static 方法完全有可能需要您的一些配置作为输入才能工作。 In this case you should opt for the following design:在这种情况下,您应该选择以下设计:

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);
  }
}

Use...利用...

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

Update: Sorry, this was based on the assumption, that Configuration had been already injected in更新:对不起,这是基于假设,配置已经被注入

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM