In this article we discuss how to read connection string dynamically in ASP .NET Core. Before starting this article please go through the link How to read connection string in ASP .NET Core.
Earlier we fetch the connection string from appsettings.json file using Dependency Injection. But here in this example we see how we set the connection string globally and use anywhere in the application without declaring each time.
Let's take ASP .NET Core MVC application and see how we set connection string dynamically and access it anywhere in the application.
➥ Open Visual Studio ➪ New Project ➪ ASP .NET Core Web Application ➪ Choose MVC as template
➥ Open the appsettings.json file and add the your connection string like below;
Earlier we fetch the connection string from appsettings.json file using Dependency Injection. But here in this example we see how we set the connection string globally and use anywhere in the application without declaring each time.
Let's take ASP .NET Core MVC application and see how we set connection string dynamically and access it anywhere in the application.
➥ Open Visual Studio ➪ New Project ➪ ASP .NET Core Web Application ➪ Choose MVC as template
➥ Open the appsettings.json file and add the your connection string like below;
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"ConnectionStrings": { | |
"DefaultConnection": "Server=**********;Database=Customers;User Id=sa;password=*******" | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public IConfigurationRoot ConfigurationRoot { get; set; } | |
public static string ConnectionString { get; private set; } | |
public Startup(IConfiguration config,IWebHostEnvironment env) | |
{ | |
ConfigurationRoot = new ConfigurationBuilder() | |
.SetBasePath(env.ContentRootPath) | |
.AddJsonFile("appSettings.json") | |
.Build(); | |
} |
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.
➥ Read the connection string value inside configure() method of startup.cs class.
![]() |
Fig-1 |
![]() |
Fig-2 |
</> Find the Source Code in Github.com/CoreProgramm/
Summary