首页 > 代码库 > Catel帮助手册-Catel.Core:(3)配置说明

Catel帮助手册-Catel.Core:(3)配置说明

 

 

 

Catel可以让你更方便的配置所有的平台

下面的表格解释了每个平台使用何种技术来获取和存储配置值。

平台 技术
.NET ConfigurationManager.AppSettings
Sliverlight IsolatedStorageSettings.ApplicationSettings
WinRT ApplicationData.Current.LocalSettings
PCL 不支持

 

1 从配置中获取值

   使用如下代码从配置中获取值:

var configurationService = new ConfigurationService();var mySetting = configurationService.GetValue<int>("mySetting", 42);

注意:

It‘s best to retrieve the service from the dependency resolver or let it be injected into the classes using it

2 设置值到配置项目中

  使用如下的代码存储值到配置中:

var configurationService = new ConfigurationService();configurationService.SetValue("mySetting", 42);

注意:

It‘s best to retrieve the service from the dependency resolver or let it be injected into the classes using it

3 自定义值的存储方式

ConfigurationService是用于扩展的,尽管他默认的是.NET的本地存储系统,它很容易的去创建自定义服务,下面是一个创建自定义服务来存储或者读取数据库的例子。

 

public class DbConfigurationService : ConfigurationService{    protected override bool ValueExists(string key)    {        using (var context = new ConfigurationContext())        {            return (from config in context.Configurations                    where config.Key == key                    select config).Any();        }    }     protected override string GetValueFromStore(string key)    {        using (var context = new ConfigurationContext())        {            return (from config in context.Configurations                    where config.Key == key                    select config.Value).First();        }    }     protected override void SetValueToStore(string key, string value)    {        using (var context = new ConfigurationContext())        {            var configuration (from config in context.Configurations                    where config.Key == key                    select config).FirstOrDefault();             if (configuration == null)            {                configuration = context.CreateObject<Configuration>();                configuration.Key = key;            }             configuration.Value = value;            context.SaveChanges();        }    }}
注意:

  不要忘记在ServiceLocator中注册自定义的ConfigurationService.

Catel帮助手册-Catel.Core:(3)配置说明