【问题标题】:How can I use the appsettings.json in static class in net 6 class library如何在 net 6 类库的静态类中使用 appsettings.json
【发布时间】:2022-01-23 09:57:17
【问题描述】:

我想在类库中的静态类中使用 appsettings.json 值 现在我知道如何像这样将 json 值绑定到 program.cs 中的类

程序.cs

ConfigurationManager configuration = builder.Configuration;
builder.Services.Configure<APConfig>(configuration.GetSection(APConfig.Position));

APConfig.cs

public class APConfig
{
    public const string Position = "APConfig";

    public string RootPath { get; set; }
    public string API_URL { get; set; }
    public string TOKEN { get; set; }
    public string pwdkey { get; set; }
    public string pwdkey1 { get; set; }
    public string pwdkey2 { get; set; }

    public string GetProperty(string keyStr)
    {
        string value = Utility.DecryptTagContent((string)this.GetType().GetProperty(keyStr).GetValue(this));

        return value;
    }
}

如何在静态类中使用绑定的 APConfig?

我找到了解决办法:

public static class HttpContext
{
    private static IHttpContextAccessor _accessor;

    public static Microsoft.AspNetCore.Http.HttpContext Current => _accessor.HttpContext;

    internal static void Configure(IHttpContextAccessor accessor)
    {
        _accessor = accessor;
    }
}

public static class StaticHttpContextExtensions
{
    public static void AddHttpContextAccessor(this IServiceCollection services)
    {
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    }

    public static IApplicationBuilder UseStaticHttpContext(this IApplicationBuilder app)
    {
        var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
        HttpContext.Configure(httpContextAccessor);
        return app;
    }
}

然后使用

HttpContext.Current.Session.SetString(key, value);
HttpContext.Current.Session.GetString(key);

【问题讨论】:

  • 你的类不应该是静态的。
  • 所以我都应该使用 DI 来代替?
  • 是的,然后将 IConfiguration 注入到你的类中。
  • 可以使用静态方法,如果您从 DI 检索 APConfig 实例并将其传递给该方法。 Services.Configure&lt;APConfig&gt;APConfig 注册为具有 DI 的服务,并指定其属性应从 IConfiguration 中的设置填充,无论它们来自何处 - 而不仅仅是 appsettings.json。这用于更容易生成依赖于设置对象的服务

标签: c# blazor class-library .net-6.0


【解决方案1】:

访问配置需要IConfiguration的实例,可以使用依赖注入获得。

你的类应该是非静态的并且有一个 DI 构造函数。

【讨论】:

    【解决方案2】:

    我也喜欢静态访问配置值。

    这个 StackOverflow 问题有几个可能有用的答案:ASP.NET Core—access Configuration from static class

    关键是您需要在启动时运行的代码,将IConfiguration 对象或其值分配给静态变量。

    然后您可以遍历这些值并将它们放在静态列表中。类似于 public static List&lt;KeyValuePair&lt;string, string&gt;&gt; Config= _config.AsEnumerable().ToList(); 或者你可以将这些值放在 public static ReadOnlyDictionary&lt;string, object&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-21
      • 1970-01-01
      • 2020-04-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多