RichaS
RichaS

Reputation: 219

How to set environment specific properties in c#?

I have a project where I want to store my data in different tables based on different environments, which can be set using 'npm config set true'

For example, I want to write my data to Table1_Dev in Dev environment and to Table1_Prod in prod environment.

I want to define my configuration properties per environment in a configuration file and then read it as per the environment in my c# code.

I can do it easily in Typescript, but I can't find a good way to do it in C#. Can you please help me with this?

Upvotes: 1

Views: 745

Answers (2)

Rahul
Rahul

Reputation: 77846

Table1_Dev in Dev environment and to Table1_Prod in prod environment.

That's wrong, rather you should have separate DB instance for different environment and target them.

You can define separate XML or JSON configuration file like Configuration_DEV.json. Have you environment specific properties there. In your code read the json file and deserialize to a setting class accordingly.

Example Configuration_DEV.json

{
  "DevSettings": {
    "DBConnectionString": "some value",
    "DatabaseName": "DevDB"
  }
}

You can define a class like

public class DevSettings
{
  public string DBConnectionString { get; set; }
  public string DatabaseName { get; set; }
}

Upvotes: 1

Helpha
Helpha

Reputation: 481

You can do this in the web.config file like so

 <appSettings>
    <add key="" value="" />
</appSettings>

Then you can reference it is your code.

What you can do next is setup publishing profiles to overwrite the key for each environnement.

Then you have to add a .config overwrite for the profile you've just created.

In the overwrite .config you can do this

  <appSettings>
    <add key="" value="" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" /> 
</appSettings>

https://msdn.microsoft.com/en-us/library/dd465318(v=vs.100).aspx

Upvotes: 0

Related Questions