存储应用程序范围值(例如 AppData 文件夹的路径)的推荐方法是什么?

问题描述 投票:0回答:1

我正在开发一个 C# 应用程序,需要在 MVVM 项目中存储应用程序范围的值,例如其 AppData 文件夹的路径。实现这一目标的推荐方法是什么?我对 C# 非常陌生,不知道编码方面的最佳实践。

我读过的内容可能可以应用?

  1. 应用程序配置
  2. 单例
  3. 依赖注入
c# windows architecture coding-style directory-structure
1个回答
0
投票

我会创建一个类:

   public class MyInfoClass
   {
    private string path1;
    public string Path1 { 
        get {
            if (path1 == null)
            {
                // load my var
                path1="my path";
            }
            return path1;
        }            
        set => path1 = value; }
   }

在 Program.cs 中注册为单例

   builder.Services.AddSingleton<MyInfoClass>();

然后您可以从应用程序中的任何位置注入并访问路径。 尽管如果值发生更改,您可以添加事件处理程序。

如果要在 Program.cs 中设置 Path1,请使用:

// 从配置中检索值(假设“MyInfoClass:Path1”是配置键)

string pathValue = _configuration["MyInfoClass:Path1"];

// 将MyInfoClass注册为单例并传递路径值

services.AddSingleton<MyInfoClass>(provider => new MyInfoClass { Path1 = pathValue })

;

© www.soinside.com 2019 - 2024. All rights reserved.