Eunice Rayas
Eunice Rayas

Reputation: 11

Dynamic connection strings appsettings.json Asp.NetCore

I'm really new in this API development, so I have the next question.

Is it possible to get the DB name at run time for my connection string? This because the user will be sending the DB name through a Json file. I'm working with Visual Studio 2019, NetCore 3.1.

I have my appsettings.json like this:

"ConnectionStrings": {
    "ImportConnection": "Data Source=SQLSERVER;Initial Catalog={dbName};User ID=Id;Password=Pass;MultipleActiveResultSets=True"
  },

And my Startup.cs in configureservices I have this

services.AddDbContext<ApplicationDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ImportConnection")));

The user send a Json file with the next structure

{
    "ImportTypeId": 1,
    "Data": [
        {
            "LayoutID": 6,
            "ClientID": "XXX",

Where ClientID is the DB name.

I really want to know if there's a way to replace the Initial Catalog {dbName} in my connectionString with the ClientID value.

Also this is my DbContext

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace API_Test.Models
{
    public class ApplicationDBContext : IdentityDbContext<ApplicationUser>//DbContext
    {
        public ApplicationDBContext(DbContextOptions<ApplicationDBContext> options) : base(options)
        {

        }
        public DbSet<DataModel> API_DATA { get; set; }
    }
}

Thank you so much

Upvotes: 1

Views: 2839

Answers (1)

Durga Prasad
Durga Prasad

Reputation: 989

You can make use of the SqlConnectionStringBuilder class in conjunction with command line arguments to meet the requirement. The solution provided does not treat the command line input as a json though. It expects the input to be a normal command line parameter. I would recommend you to revisit that again and check if your user can convert the json to list of parameters and pass it along to application

So, lets say the user runs the application with following parameters:

dotnet run --ClientID XXX

Inside of Program.cs, ensure the commandline args are passed into the CreateDefaultBuilder() method, because this is the method which internally parses all the commandline args and adds them to the configuration object.

public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });

With that in place, you can now override the database value inside of your startup.cs as shown inline:

SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(Configuration.GetConnectionString("ImportConnection"));

if (!string.IsNullOrEmpty(Configuration.GetValue<string>("ClientID")))
{
    builder.InitialCatalog = Configuration.GetValue<string>("ClientID");
}

services.AddDbContext<ApplicationDBContext>(options => options.UseSqlServer(builder.ConnectionString));

Upvotes: 1

Related Questions