Menu Close

How to set Connection String Globally in ASP .NET Core

In this article we discuss how to set Connection String Globally in ASP .Net Core. Following this article it should clear how to Find Connection String in ASP .NET Core. Please read my previous article AddMVC() vs AddControllersWithViews() vs AddControllers() vs AddRazorPages() in ASP .NET Core 3.x.

Generally, in ASP .NET Core application we fetch the connection string from appsettings.json file using Dependency Injection. But using this article we will see how to 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 to set connection string dynamically in ASP.Net Core and access it anywhere in the application.

Creating ASP.NET Core Application

Here in this example we are going to develop ASP.NET Core Web Application for that we are going to choose “ASP.NET Core Web Application” template.

Create ASPNet Core project

Further on the next step set the project name like “SetGlobalConnection” (or you can set any name as per your convenient) and then choose location of project. Select ASP .NET Core Version 3.1 as a framework for application and remember few advance settings for such as configuring https and docker we are not enable for now so unchecked the settings for this project and then click the Create button.

aspnetcore template

The project structure of the ASP.NET Core MVC application is look like below;

aspnetcore project

Adding the Connection String in Appsettings.json file.

We need to add the connection string inside the appsettings,json file as like below;

"ConnectionStrings": {
    "DefaultConnection": "Server=**********;Database=Customers;User Id=sa;password=*******"
  }

How to set the connection string Globally and access in entire application

To declare the connection string globally we need to customize the startup.cs class like below;

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();
        }

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.
  • Here appsettings.json file is dynamically loaded when the startup class is called.

To Read the connection string value  inside configure() method of startup.cs class we need to access the static variable like below;

ConnectionString = configRoot.GetConnectionString("DefaultConnection");
dynamic connection string

Now we have set the connection string dynamically in startup.cs class. Let’s go to the Controller page and access it inside the HomeController.cs File like below;

public IActionResult Index()
        {
            string myconn = Startup.ConnectionString;
            return View();
        }
global connection

You can see that, the connection string now accessible in the controller page by just accessing the startup.connectionstring as inside we declare the connection string variable as static and append the connection string into it inside configure() method.

Video Tutorial

Conclusion

Leave behind your valuable queries and suggestions in the comment section below. Also, if you think this article helps you, do not forget to share this with your developer community. Happy Coding 🙂

Jayant Tripathy
Coder, Blogger, YouTuber

A passionate developer keep focus on learning and working on new technology.

2 Comments

  1. Kamrul

    Hello,Thank u for the great content. I just want to know how to add the code in case of .net core 6 where there is no startup class. Thank u

  2. admin

    Hi Kamrul, Thanks for your question.

    From .NET Core 6 onwards startup.cs is not present, but we have the Program.cs file where we can add the required services and middleware efficiently. Please follow one of the posts about .NET Core 6, I hope you can get an idea of this.

    https://jayanttripathy.com/microservices-architecture-in-asp-net-core-6/

    Program.cs file:

    https://github.com/JayantTripathy/microservices-api-gateway/blob/master/Ecommerce-APIGateway/Program.cs

Leave a Reply

Your email address will not be published.