Header add

coreprogram
In this article we discuss how to set Connection String Globally 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;

➥ Inside the Startup class we go to add appsettings.json file dynamically in the root element and access the connection string in a variable in the configure() method.

Code Snippet Explanation

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
That's it. Now if we want access the connection string inside any controller then follow like below;

Fig-2




</> Find the Source Code in Github.com/CoreProgramm/
    Summary
 In this tutorial we discussed how to set Connection String Globally in ASP .NET Core. If have any question related to this topic then give your feedback.

You May Also Like...

Post a Comment

Previous Post Next Post