.Net Core Connection String

In ASP.NET Core the configuration system is very flexible, and the connection string could be stored in appsettings.json. In this blog, this blog shows asp.net core how to use the connection string stored in appsettings.json.

Config appsettings.json file

To define the connection strings in appsettings.json it is important to specify it in the right section of the JSON structure. Below snippet shows how to store connection string in appsettings.json file

{
“Logging”: {
“LogLevel”: {
“Default”: “Warning”
}
},
“AllowedHosts”: “*”,
“ConnectionStrings”: {
“Dev”: “Server=myServer;Database=dev;Trusted_Connection=True;”,
“Live”: “Server=myServer;Database=live;Trusted_Connection=True;”
}
}

Read connection string from appsettings.json file

For Entity Framework Core, we can use the Configuration API to pass the connection string to the DbContext in the Startup class:

public void ConfigureServices(IServiceCollection services) {
if (CurrentEnvironment.IsDevelopment())
{
services.AddDbContext(options => { options.UseSqlServer(Configuration.GetConnectionString(“Dev”)); });
}
else {
services.AddDbContext(options => { options.UseSqlServer(Configuration.GetConnectionString(“Live”)); });
}
}

Not Entity Framework

If you are not an Entity Framework Core fan, then you can create a interface with property to store the connection string.

public interface IDBInfo
{
string DbConnectionString { get; }
}

In the Startup class we can use AddScoped method to read data from json file to interface:

public void ConfigureServices(IServiceCollection services) {
if (CurrentEnvironment.IsDevelopment())
{
services.AddScoped(x => new DBInfo(Configuration.GetConnectionString(“Dev”)));
}
else {
services.AddScoped(x => new DBInfo(Configuration.GetConnectionString(“live”)));
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *