Looking for the best practice in c# program for using constant depends on running env (dev/prod)
I used const values but the problem is when switching environment.
Looking for a good DP/OOP idea.
CodePudding user response:
The simplest way to achieve this would be to create separate Config
files for different environments.
Let's say you have Config.dev.json
and Config.prod.json
files.
Both files contain the same data structure, but with different values for each environment.
You could use the appsettings.json
file as an example.
Then you can use the Config
file as a source of your constants values.
CodePudding user response:
This depends on what kind of constant you mean. Within C# there are different kinds of constants/readonly values.
- Compile time constant (E.G.
const int Two = 2
) - Runtime constant
- fields (E.G.
readonly int Two = 2
) - properties (E.G.
int Two { get; } = 2
orint Two => 2
)
- fields (E.G.
All of these values can be regarded as 'constant' as they can't change value during runtime. More info here: What is the difference between const and readonly in C#?
Usually when specifying environment-specific values, this is done via a configuration file.
In newer .Net (core) versions, you can use appsettings.json
. This provides the option to add appsettings.Development.json
and appsettings.Production.json
, which can contain the respective values.
When using the default configuration provider of .net core, the system will choose the appsettings file corresponding to your Microsoft.Extensions.Hosting.IHostEnvironment
.
When you're not able to use appsettings files for some reason, you can also use the HostEnvironment to make a switch:
private IHostEnvironment _hostEnvironment;
int Two => _hostEnvironment.IsDevelopment() ? 3 : 2;
// or
int Two => _hostEnvironment.IsEnvironment("Development") ? 3 : 2;
More info on environments and appsettings here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-6.0
If you actually do require a compile time constant, your only option is to use pragma's. For example:
#if DEBUG
const int Two = 3;
#else
const int Two = 2;
#endif
When doing so, you need to compile the application with configuration 'Debug' for your Development application and with configuration 'Release' for your production application.
More info on pragma's (preprocessor directives) here: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives