Is it possible to have different configuration set for the same key for multiple console apps on windows?

50 Views Asked by At

I have couple of console apps which have the same key in appsettings.json (ConnectionString). I need to centralise these connection strings on the machine. The best place I can think of to use Environment Variables. These both console apps need to target different databases. I need a way to set key values to different databases. If this was an IIS application then I could use location tag in applicationhost.config to set different values for them. Can similar approach be used for console apps?

1

There are 1 best solutions below

0
Guru Stron On

– How do you start the console apps?
Process.Start from another console app.

And

Using different connection string names is not an option! This is the same application deployed in 2 different locations.

You need to either implement some magic by hand - for example you can store connection string name in appsettings.json:

{
   "ConnectionStringName":"App1ConnectionString"  // App2ConnectionString for the second one
}

and the connection string itself in appropriately named environment variable - ConnectionStrings__App1ConnectionString and ConnectionStrings__App2ConnectionString accordingly. And in the app you will do something like:

var connectionStringName = configuration.GetValue<string>("ConnectionStringName");
var connectionString = configuration.GetConnectionString(connectionStringName);

But since you are using Process.Start you can pass the connection string as a parameter for your app. For example in the app:

var builder = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", optional: true)
    // ...
    .AddEnvironmentVariables() 
    .AddCommandLine(args); // order is important the last added source will have a precedence. 

var connectionString = builder.Build().GetConnectionString("myConnStringName");
Console.WriteLine(connectionString);

And on the calling side provide the parameter - something like:

var processStartInfo = new ProcessStartInfo
{
    // ...
    Arguments = "..." + " --ConnectionStrings:myConnStringName=ConnStr1"
};