How to get connectionstring from appsettings.json instead of being hardcoded in .NET Core

By FoxLearn 11/1/2024 1:59:23 PM   186
In .NET Core, it's a good practice to store your connection strings in the appsettings.json file instead of hardcoding them in your code.

How do I avoid hardcoded connection string in my DbContext class?

For example:

public class TestDbContext : DbContext
{
  protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  {
    // hardcoded
    optionsBuilder.UseSqlServer("Server=.;Database=DbName;User Id=myUser;Password=myPassword;MultipleActiveResultSets=true;");
  } 
  //...
}

.NET Core get connection string from appsettings.json

To avoid hardcoding connection strings in your DbContext class in .NET Core, follow these steps:

Open your appsettings.json file and add a section for connection strings.

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=.;Database=DbName;User Id=myUser;Password=myPassword;MultipleActiveResultSets=true;"
  }
}

Using connection string from appsettings.json to startup.cs

You can read the connection string from the appsettings.json file in your application by using dependency injection. Here’s an example of how to do this in your Startup.cs or wherever you configure your services:

public class Startup
{
    public IConfiguration Configuration { get; }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    //How to get ConnectionString from appsettings.json file?
    public void ConfigureServices(IServiceCollection services)
    {
        var connectionString = Configuration.GetConnectionString("DefaultConnection");
        services.AddDbContext<MyDbContext>(options =>
            options.UseSqlServer(connectionString));
    }
}

We will retrieve the connection string from IConfiguration and pass it to your DbContext through its constructor.

In your DbContext, use the provided options without hardcoding the connection string.

public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options)
        : base(options)
    {
    }
}

The ConfigurationBuilder in .NET Core is used to assemble various configuration settings from sources like JSON files, INI files, and environment variables. You can add a connection string to the appsettings.json file and read it using ConfigurationBuilder.

To use AddJsonFile, you need to install the Microsoft.Extensions.Configuration.Json package via NuGet.

public class MyDbContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        // Get ConnectionString from appsettings.json
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
            .AddJsonFile("appsettings.json")
            .Build();

        optionsBuilder.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));
    }

    public DbSet<Person> People { get; set; }
}

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

This setup allows you to easily manage and access configuration settings, including connection strings, in your .NET Core applications.