Was trying to follow a tutorial here for a console app https://www.connectionstrings.com/store-and-read-connection-string-in-appsettings-json/
So in my appsettings-json i have:
{
"ConnectionStrings": {
"myDb1": "Server=myServer;Database=myDb1;Trusted_Connection=True;",
}
}
My program:
using System;
using Microsoft.Extensions.Configuration;
namespace mynamespace
{
class Program
{
string myDb1ConnectionString = _configuration.GetConnectionString("myDb1");
static void Main(string[] args)
{
...
}
}
}
The error I get is : "The name '_configuration' does not exist in the current context".
CodePudding user response:
The page you link to isn't a tutorial, it only shows how to read a connection string from any configuration provider, not just appsettings.json. It assumes you've already built a configuration object. .NET (Core) 5 and 6 use far simpler code though.
Check Configuration in .NET to understand how configuration really works. You can find more detailed information on the various config providers, how they're used and how to create your own in Configuration in ASP.NET Core
Using a generic host
In .NET 6, the current long term version, a minimal application would need:
using Microsoft.Extensions.Hosting;
using IHost host = Host.CreateDefaultBuilder(args).Build();
var configuration=host.Services.GetRequiredService<IConfiguration>();
var connectionString=configuration.GetConnectionString("blahblah");
...
As the docs explain, CreateDefaultBuilder
will load configuration settings from any appsettings.json files, environment variables and finally command-line parameters.
This means you can override the settings stored in the JSON files by specifying the new values using environment variables or CLI parameters, eg :
dotnet run /ConnectionStrings:blahblah="......."
Without a generic host
You can create just the Configuration object by using a ConfigurationBuilder:
IConfiguration config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables()
.AddCommandLine(args)
.Build();
var connectionString=configuration.GetConnectionString("blahblah");