Friday 2 October 2020

Dynamic Connection String In .NET Core

 To read connection string/keys from appsettings.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.

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.

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.

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

No comments:

Post a Comment