将应用程序配置数据存储到静态列表中

时间:2017-09-11 05:39:59

标签: c# wpf mvvm static

我在WPF应用程序中实现MVVM,我很难决定在何处以及如何存储我的配置数据(从xml文件加载),因此可以在每个View Model中访问它。所以我想出的是:

static class Configurations
{
    private static List<object> Container = new List<object>();

    public static void LoadConfigurations() { }
    public static List<object> GetConfiguration(string configuration)
    {
        -- return the needed subelement --
        return Container(configuration);
    }

}

我正在考虑使用静态类,因为可以在视图模型之间传递任何数据的情况下访问它。 我只需要在应用程序启动时调用 Configurations.LoadConfigurations(),并在需要时调用 Configurations.GetConfigurations()

所以我的问题是,这是处理这种情况的好方法还是不好的做法?

不要介意代码的正确性,它仅用于示例目的。

1 个答案:

答案 0 :(得分:1)

  

所以我的问题是,这是处理这种情况的好方法还是不好的做法?

取决于:)但是如果您希望能够对视图模型进行单元测试,那么您还希望能够模拟配置设置。在这种情况下,最好使用注入视图模型类的共享服务。

该服务应实现一个接口:

public interface IConfiguration
{
    List<object> GetConfiguration(string configuration);
}

public class Configurations : IConfiguration
{
    private readonly List<object> Container = new List<object>();

    public List<object> GetConfiguration(string configuration)
    {
        -- return the needed subelement --
        return Container(configuration);
    }
}

然后,您可以在单元测试中简单地提供此接口的另一个实现:

IConfiguration config = new Configurations(); //or any other implementation...
ViewModel vm = new ViewModel(config);

查看型号:

public class ViewModel
{
    public ViewModel(IConfiguration config)
    {
        var config = config.GetConfiguration("...");
        //...
    }
}
相关问题