User Configuration Settings in .NET Core

后端 未结 1 2070
有刺的猬
有刺的猬 2021-02-13 10:10

I spent all day yesterday researching this and cannot find any reasonable solution.

I\'m porting a .NET Framework project to .NET Core 2.0. The project used user setting

1条回答
  •  离开以前
    2021-02-13 10:42

    I created a static class that the user could access anywhere if needed. This isn't perfect but it is strongly typed, and only creates when the accesses the default property.

    I was going to use DI to put the config into the properties of each class, but in some cases I wanted to have the class in the constructor.

    Use:

    public MainWindow()
    {
        InitializeComponent();
    
        var t = AppSettings.Default.Theme;
        AppSettings.Default.Theme += "b";
        AppSettings.Default.Save();
    }
    

    The class:

    using Microsoft.Extensions.Configuration;
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Text;
    
    namespace TestClient
    {
    
        public class AppSettings
        {
            private AppSettings()
            {
                // marked as private to prevent outside classes from creating new.
            }
    
            private static string _jsonSource;
            private static AppSettings _appSettings = null;
            public static AppSettings Default
            {
                get
                {
                    if (_appSettings == null)
                    {
                        var builder = new ConfigurationBuilder()
                            .SetBasePath(Directory.GetCurrentDirectory())
                            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
    
                        _jsonSource = $"{Directory.GetCurrentDirectory()}{Path.DirectorySeparatorChar}appsettings.json";
    
                        var config = builder.Build();
                        _appSettings = new AppSettings();
                        config.Bind(_appSettings);
                    }
    
                    return _appSettings;
                }
            }
    
            public void Save()
            {
                // open config file
                string json = JsonConvert.SerializeObject(_appSettings);
    
                //write string to file
                System.IO.File.WriteAllText(_jsonSource, json);
            }
    
            public string Theme { get; set; }
        }
    }
    

    0 讨论(0)
提交回复
热议问题