.NET Core Settings - the best practice

Viewed 3885

In the .NET Framework I was used to use settings from Properties - Settings (Properties.Settings.Default.SomeSettingsValue). It was very easy and clean to use. I'm starting to use .NET Core now, but there is not any settings like this. I found some solutions but none of them was so clean and simple like the old one.

What is the best practice and solution for the settings in .NET Core?

Thank you.

2 Answers

I think you are looking for the Options pattern

  1. Add a setting to your appsettings.json: "setting1": "test setting".
  2. Create a class: public class AppSettings {
    public string Setting1 { get; set; } }
  3. Add the services.Configure<AppSettings>(Configuration); to your startup.cs
  4. Now you can inject IOptions<AppSettings> appSettings in the classes you need those options

You should use the ASP.Net Core Configuration API. For example, you can add configuration settings to the appsettings.json file, which is usually automatically added to your project when you first create it, for example:

{
    "Logging": {
        "LogLevel": {
            "Default": "Information"
        }
    },
    "ConnectionStrings": {
        "MyDatabase": "Server=Server1;Database=MyDatabase;Integrated Security=false;",
    },
}
Related