Dynamic Connection String In .NET Core

To read connection string/keys from appsettigs.json file follow the below steps.

Put your connection string in appsettings.json file

In ASP.NET Core, configuration API provides a way of configuring an app based on a list of name-value pairs that can be read at runtime from multiple sources. Please note that class libraries don’t have an appsettings.json by default. The solution is simple --   access appsettings.json key-value pairs in your project through Dependency Injection principle in ASP.NET Core.

appsettings.json\
 
Write the below code to Startup.cs file.
  1. public IConfigurationRoot Configuration {  
  2.     get;  
  3.     set;  
  4. }  
  5. public static string ConnectionString {  
  6.     get;  
  7.     private set;  
  8. }  
  9. public Startup(IHostingEnvironment env) {  
  10.     Configuration = new ConfigurationBuilder().SetBasePath(env.ContentRootPath).AddJsonFile("appSettings.json").Build();  
  11. }  
IConfiguration has two specializations,
  • IConfigurationRoot is used for root node. It can trigger a reload.
  • IConfigurationSection Represents a section of configuration values. The GetSection and GetChildrenmethods return an IConfigurationSection.
  • Use IConfigurationRoot when reloading configuration or for access to each provider.
In Configure method of Startup.cs class, put the below line.
  1. ConnectionString = Configuration["ConnectionStrings:DefaultConnection"];  
Sensitive configuration settings like connection strings should only be stored outside the version control repository (for example- in UserSecrets or Environment Variables) but hopefully you get the idea.

In Context class put this method.

Here simply call our Startup class property using Startup(Class).Property which you set in startup.cs class.
  1. public static string GetConnectionString()  
  2. {  
  3.    return Startup.ConnectionString;  
  4. }  
And that's all. Now, you can use a dynamic connection string in your project.

At the end your startup.cs file looks like this.
  • .SetBasePath()
    It sets the FileProvider for file-based providers to a PhysicalFileProvider with the base path.

  • .AddJsonFile()
    We need to include the Microsoft.Extensions.Configuration.Json NuGet package if you want to call the.AddJsonFile() method.

  • ConfigurationBuilder Class
    Used to build key/value based configuration settings for use in an application.
Startup.cs 
 
And your context file looks like this,

And using GetConnectionString() method we are going to call Startup class method, namely ConnectionString, which returns our connection string.

UseSqlServer is an extension method in the namespace Microsoft.Data.Entity so, you need to import that into your code, like this:

  1. using Microsoft.EntityFrameworkCore;   
 
Output 
 Output
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now