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
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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

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

Related

  • Unit Testing Large Codebases: Principles, Practices, and C++ Examples
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Thermometer Continuation in Scala
  • Thumbnail Generator Microservice for PDF in Spring Boot

Trending

  • AI-Driven Root Cause Analysis in SRE: Enhancing Incident Resolution
  • How To Build Resilient Microservices Using Circuit Breakers and Retries: A Developer’s Guide To Surviving
  • A Simple, Convenience Package for the Azure Cosmos DB Go SDK
  • Detection and Mitigation of Lateral Movement in Cloud Networks
  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

  • Unit Testing Large Codebases: Principles, Practices, and C++ Examples
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Thermometer Continuation in Scala
  • Thumbnail Generator Microservice for PDF in Spring Boot

Partner Resources

×

Comments

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: