Closed rajukumar-jha closed 1 year ago
Yes, you are in complete control of your reading your connection string from anywhere you like, including Key Vault.
Have read of simple-configuration-of-connection-string-through-key-vault and stackoverflow
However I don't use it and prefer to set the connection string on the web app:
I use this. In Startup.cs
, ConfigureServices function, this is what I have:
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
...
services.AddTransient<IApplicationDbContext, ApplicationDbContext>();
appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=ReversePoco;Integrated Security=true"
},
"AllowedHosts": "*"
}
appsettings.Production.json
{
}
Thank You @sjh37 for your prompt response. However, I would like to know the implementation by editing the .tt & .ttinclude files. I already have the license for Reverse POCO Generator. Editing the .tt & .ttinclue files helps us in customizing our application architecture. Now that we have a requirement that instead of reading the DefaultConnection from appsettings.json we have to integrate Key Vault so that connectionString value can be fetched from there. Need you comments on this. Thank You
In Program.cs
you should have the following
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")
?? Environments.Development;
Console.WriteLine($"EnvironmentName = {environment}");
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", false, true)
.AddJsonFile($"appsettings.{environment}.json", true, true)
.AddEnvironmentVariables()
.Build();
Notice that it loads appsettings.json
first, then adds appsettings.Production.json
, then adds your environment variables
.
It's the "environment variables" that are key here, as that is what Azure sets for you in the screenshot with configuration above.
When developing locally on your laptop the connection is read from the appsettings.json
file, then overwritten with the appsettings.Development.json
file.
In production, the connection is read from the appsettings.json
file, then overwritten with the appsettings.Production.json
file, then overwritten with the environment variables
set by Azure configuration above.
If you want to use KeyVault the same way as the above examples show, then have a read of key-vault-configuration
Code examples are plentiful on GitHub. just search for "connectionstring AddAzureKeyVault UseSqlServer"
Hi @sjh37 Is there any way to replace reading the Setting.ConnectionString from appsettings.Development.json to Key Vault? Please share your thoughts. Thank You