.NET Core 中的用户配置设置 [英] User Configuration Settings in .NET Core

查看:27
本文介绍了.NET Core 中的用户配置设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我昨天花了一整天研究这个,但找不到任何合理的解决方案.

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

我正在将 .NET Framework 项目移植到 .NET Core 2.0.该项目使用用户设置 (Properties.Settings.Default) 来存储某些信息,这些信息在每次应用程序启动时都保持不变.它还可以更新此信息(例如用户偏好选项).

I'm porting a .NET Framework project to .NET Core 2.0. The project used user settings (Properties.Settings.Default) to store certain information that persisted through each application launch. It could also update this information (e.g. user preference options).

我的理解是 .NET Core 中不存在?那么如何才能实现这一目标呢?我能找到的最接近的事情是安装一些 NuGet 包并使用 Microsoft.Extensions.Configuration,但是,这与 .NET 框架.

My understanding is that is does not exist in .NET Core? So how is it possible to achieve this? The closest thing I could find was installing a few NuGet packages and using Microsoft.Extensions.Configuration, however, this is not even close to Properties.Settings.Default in the .NET Framework.

首先,它需要一个文件(JSON、XML,你有什么)位于运行文件的目录中.这似乎很疯狂,尤其是在安全信息的情况下.此外,当我的项目的内部库应该能够处理所有配置文件时,我不想将配置文件与项目一起推送,就像它在 .NET Framework 中所做的那样.

First, it requires a file (JSON, XML, what have you) to be in the running file's directory. This seems insane, especially in the case of secure information. In addition, I don't want to push a config file with the project when internal libraries of my project should be able to handle all of it, as it did with .NET Framework.

我意识到有环境变量,但我无法在我的一生中加载它们.老实说,这应该是一个简单的过程,所以我不确定我是否遗漏了一些明显的东西.在这里,在我的库的属性">调试"部分,有一个名为环境变量"的部分,我在其中添加了两个值.

I realize there are Environment Variables, but I cannot get them to load in for the life of me. It honestly should be a simple process so I'm not sure if I'm missing something blatantly obvious. Here, in the Properties>Debug section of my library, there is a section called "Environment variables" which I have added two values in.

我的配置对象如下所示:

My configuration object looks like so:

private static IConfiguration Configuration { get; } = new ConfigurationBuilder()
    //.SetBasePath(Directory.GetCurrentDirectory())
    //.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddEnvironmentVariables()
    .Build();

为了访问变量,我尝试了以下方法:

To access the variables, I have tried these ways:

Configuration.GetSection("SettingName").Value;
Configuration["SettingName"];
Environment.GetEnvironmentVariable("SettingName");

它们都返回空.

另外,有没有办法保存属性?我知道它的设计是为了减轻重量,但肯定有办法节省吗?

Also, is there no way to save a property? I understand it was designed to be light weight, but surely there is a way to save?

我试过了:

Configuration["SettingName"] = "Value";
Environment.SetEnvironmentVariable("SettingName", "Value");

它似乎更新内存,而不是文件本身,这使得持久性设置无用.

It seems to update the memory, but not the file itself, which leaves persistant settings useless.

如何在库中读取和保存用户设置,同时将其全部包含在该库中?

How can I read and save user settings in a library, while having it all contained within that library?

推荐答案

我创建了一个静态类,用户可以在需要时在任何地方访问它.这并不完美,但它是强类型的,并且仅在访问默认属性时创建.

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.

我打算使用 DI 将配置放入每个类的属性中,但在某些情况下,我希望在构造函数中包含该类.

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.

使用:

public MainWindow()
{
    InitializeComponent();

    var t = AppSettings.Default.Theme;
    AppSettings.Default.Theme += "b";
    AppSettings.Default.Save();
}

班级:

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; }
    }
}

这篇关于.NET Core 中的用户配置设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆