ASP.NET Core——从静态类访问配置 [英] ASP.NET Core—access Configuration from static class
本文介绍了ASP.NET Core——从静态类访问配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要一个访问配置对象的简单静态类.所有配置信息都已从 Startup 类的 appsettings.json 文件中读取.我只需要一种简单的方法来访问它.这可能吗?
I want a simple static class that accesses the Configuration object. All the config info is already read in from the appsettings.json file in the Startup class. I just need an easy way to access it. Is this possible?
namespace MyNamespace
{
public static class Config
{
public string Username => Configuration["Username"];
public string Password => Configuration["Password"];
}
}
应用中的其他任何地方:
Anywhere else in the app:
string username = Config.Username;
string password = Config.Password;
推荐答案
略短的版本,原理同上...
A slightly shorter version based on the same principle as above...
public Startup(IConfiguration configuration)
{
Configuration = configuration;
StaticConfig = configuration;
}
public static IConfiguration StaticConfig { get; private set; }
在另一个静态类中使用:
To use in another static class:
string connString = Startup.StaticConfig.GetConnectionString("DefaultConnection");
这篇关于ASP.NET Core——从静态类访问配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文