I have a new ASP.NET Core 8 MVC project using Visual Studio 2022.
In appsettings.json
, I have a connection string:
"ConnectionStrings": {
"MyDB": "...connecting...details...."
}
I can use dependency injection in my controllers to read this value:
private IConfiguration _AppSettingsConfig;
public PocController(IConfiguration config)
{
_AppSettingsConfig = config;
}
and then use it
_AppSettingsConfig.GetConnectionString("MyDB")
or
_AppSettingsConfig["ConnectionStrings:MyDB"];
That works, however, I want to replace these 5 lines with a class that contains a static property that will wrap around this and return the appsettings.json
value.
public class ConfigProps
{
public static string MyDBConString
{
get
{
return "how do I get from here to the config?";
}
}
}
Is there a way to do this?
You could still get it by using the ConfigurationBuilder to load the json file and then read it by using the GetConnectionString method.
More detials you could refer to below codes:
public class ConfigProps
{
private static readonly IConfiguration _config;
static ConfigProps()
{
_config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
}
public static string MyDBConString
{
get
{
return _config.GetConnectionString("DefaultConnection");
}
}
}
Result: