Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

How to dynamically read connection string from appsettings.json

$
0
0

I published an ASP.NET MVC Core 1.1.1 web app on a server that has identically same two SQL Server databases, MyDb1 and MyDb2. The app runs fine and correctly reads/writes data from/to MyDb1. But when I change the database name inappsettings.json from MyDb1 to MyDb2 and modify data through the app's UI, the data still gets modified in MyDb1 instead of MyDb2. What I may be missing? Following is a snapshot of my Startup.cs and appsettings.json:

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
var connection = @"Server=MyServer;Database=MyDb1;User Id=TestUser;Password=TestPswd";
services.AddDbContext<ABCTestContext>(options => options.UseSqlServer(connection));

// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();

services.AddMvc();
services.AddDistributedMemoryCache();
services.AddSession();

// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}

appsettings.json

{"ConnectionStrings": {"DefaultConnection": "Server=MyServer;Database=MyDb1;User Id=TestUser;Password=TestPswd;MultipleActiveResultSets=true"
},"Logging": {"IncludeScopes": false,"LogLevel": {"Default": "Debug","System": "Information","Microsoft": "Information"
}
}
}




Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>