I'm looking for a method to switch dynamically between production and test environment.
I have two different connection strings to MSSQL databases. I want to dynamically pass this to my dbContext:
services.AddDbContext<ViggrContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("TestDatabase")));
I have two types of publish profiles, one for Test and another for Production environment. In this profile I choose a connection to the database. Ofcourse the Test profile points to the TestDatabase connection string and the Production profile points to the Production Database.
But how can I dynamically load the Startup.cs class in this section of the code?
services.AddDbContext<ViggrContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("TestDatabase")));
Do you have any suggestions ?
You can configure different environment connection strings in different appsettings files like this-
For test environment, use appsettings. test .json
"Data": {
"ViggrContext": {
"ConnectionString": "" /*<<== TestDatabase connection string */
},
For prod environment, use appsettings. prod .json
"Data": {
"ViggrContext": {
"ConnectionString": "" /*<<== ProdDatabase connection string */
},
Use ASPNETCORE_ENVIRONMENT environment variable to set current environment as Test or Prod values.
In Startup, you can use like this-
services.AddDbContext<ViggrContext>(options =>
options.UseSqlServer(Configuration["Data:ViggrContext:ConnectionString"]));
See if this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.