DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Thermometer Continuation in Scala
  • Thumbnail Generator Microservice for PDF in Spring Boot
  • From Zero to Meme Hero: How I Built an AI-Powered Meme Generator in React

Trending

  • Recurrent Workflows With Cloud Native Dapr Jobs
  • A Guide to Container Runtimes
  • Create Your Own AI-Powered Virtual Tutor: An Easy Tutorial
  • How the Go Runtime Preempts Goroutines for Efficient Concurrency
  1. DZone
  2. Data Engineering
  3. Data
  4. Dynamic Connection String In .NET Core

Dynamic Connection String In .NET Core

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

By 
Faisal Pathan user avatar
Faisal Pathan
·
Jul. 11, 18 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
106.9K Views

Join the DZone community and get the full member experience.

Join For Free

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.

public IConfigurationRoot Configuration {  
    get;  
    set;  
}  
public static string ConnectionString {  
    get;  
    private set;  
}  
public Startup(IHostingEnvironment env) {  
    Configuration = 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.

In Configure method of Startup.cs class, put the below line.

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.

public static string GetConnectionString()  
{  
   return Startup.ConnectionString;  
}  

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

Connection string Data Types

Opinions expressed by DZone contributors are their own.

Related

  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Thermometer Continuation in Scala
  • Thumbnail Generator Microservice for PDF in Spring Boot
  • From Zero to Meme Hero: How I Built an AI-Powered Meme Generator in React

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!