7.读写配置文件和添加缓存
感觉没什么好总结的,直接上代码吧:
配置文件:
1添加一个枚举
/// <summary> /// 配置键名 /// </summary> public enum ConfigKey { /// <summary> /// 系统配置 /// </summary> SystemConfig, /// <summary> /// 缓存配置 /// </summary> CacheConfig, }
2.添加一个读写的接口
/// <summary> /// 配置管理器接口 /// </summary> public interface IConfigManager { /// <summary> /// 读取本地配置 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <returns></returns> T Read<T>(ValueType key); /// <summary> /// 保存配置到本地 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="value"></param> void Write<T>(ValueType key, T value); }
3.实现该接口
/// <summary> /// 读写配置文件 /// </summary> [ExposedService(Lifetime.Singleton, typeof(IConfigManager))] public class ConfigManager : IConfigManager { private const string root = "Config"; private string GetFullPath(ValueType key) { return Path.Combine(root, key.GetType().FullName + "." + key.ToString() + ".json"); } /// <summary> /// 读配置文件 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <returns></returns> public T Read<T>(ValueType key) { string filename = GetFullPath(key); return JsonHelper.Load<T>(filename); } /// <summary> /// 写配置文件 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="value"></param> public void Write<T>(ValueType key, T value) { Assert.NotNull(key); Assert.NotNull(value); Directory.CreateDirectory(root); string filename = GetFullPath(key); JsonHelper.Save(value, filename, true); } }
缓存:
1.添加一个枚举
/// <summary> /// 用枚举区分缓存 /// </summary> public enum CacheKey { /// <summary> /// 当前用户 /// </summary> User, /// <summary> /// 是否自动登录 /// </summary> IsAutoLogin, /// <summary> /// 是否记住密码 /// </summary> IsRemember, /// <summary> /// 缓存数据 /// </summary> AppData, /// <summary> /// 过滤器算法缓存数据 /// </summary> Filters, }
2.添加一个接口
/// <summary> /// 缓存接口 /// </summary> public interface ICacheManager { /// <summary> /// 获取缓存 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> bool Get<T>(ValueType key, out T value); /// <summary> /// 保存缓存 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="value"></param> void Set<T>(ValueType key, T value); /// <summary> /// 删存缓存 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> void Delete(ValueType key); }
3.josn帮助类 需要添加Newtonsoft.Json
/// <summary> /// Json文件的序列化和反序列化帮助类 /// </summary> public static class JsonHelper { /// <summary> /// 加载某个JSON文件并返回指定的类型实例 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="fileName"></param> /// <returns></returns> public static T Load<T>(string fileName) { if (!File.Exists(fileName)) { return default(T); } string content = File.ReadAllText(fileName); return Deserialize<T>(content); } public static T Deserialize<T>(string content) { return JsonConvert.DeserializeObject<T>(content); } /// <summary> /// 将指定的类型实例保存为JSON文件 /// </summary> /// <param name="obj"></param> /// <param name="fileName"></param> /// <param name="indented"></param> public static void Save(object obj, string fileName, bool indented = false) { string content = Serialize(obj, indented); File.WriteAllText(fileName, content); } public static string Serialize(object obj, bool indented = false) { Formatting formatting = indented ? Formatting.Indented : Formatting.None; return JsonConvert.SerializeObject(obj, formatting); } }
获取命名空间字符串
public static class ValueTypeExtension { /// <summary> /// 获取值类型的命令空间+类型名称的字符串 /// </summary> /// <param name="valueType"></param> /// <returns></returns> public static string GetFullName(this ValueType valueType) { return $"{valueType.GetType().FullName}.{valueType}"; } /// <summary> /// 获取值类型的JSON全文件名 /// </summary> /// <param name="valueType"></param> /// <returns></returns> public static string GetJsonFullName(this ValueType valueType) { return $"{valueType.GetFullName()}.json"; } }
4.实现该缓存接口
/// <summary> /// 提供缓存服务的管理器 /// </summary> [ExposedService(Lifetime.Singleton, typeof(ICacheManager))] class CacheManager : ICacheManager { private IConfigManager configManager;//读写配置文件 private Dictionary<string, string> cacheNames; private readonly object cacheLock = new object(); public CacheManager(IConfigManager configManager) { this.configManager = configManager; cacheNames = configManager.Read<Dictionary<string, string>>(ConfigKey.CacheConfig) ?? new Dictionary<string, string>(); } /// <summary> /// 获取本地缓存内容 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> public bool Get<T>(ValueType key, out T value) { value = default(T); string obj = key.ToString(); lock (cacheLock) { if (!cacheNames.ContainsKey(key.GetFullName())) return false; obj = cacheNames[key.GetFullName()]; } try { value = JsonHelper.Deserialize<T>(obj); return true; } catch (Exception ex) { return false; } } public void Set<T>(ValueType key, T value) { Assert.NotNull(key); Assert.NotNull(value); string content = JsonHelper.Serialize(value); lock (cacheLock) { if (cacheNames.ContainsKey(key.GetFullName())) { //若存在则修改 cacheNames[key.GetFullName()] = content; } else { cacheNames.Add(key.GetFullName(), content); } configManager.Write(ConfigKey.CacheConfig, cacheNames); } } /// <summary> /// 删除缓存内容 /// </summary> /// <param name="key"></param> public void Delete(ValueType key) { lock (cacheLock) { if (cacheNames.ContainsKey(key.GetFullName())) { cacheNames.Remove(key.GetFullName()); configManager.Write(ConfigKey.CacheConfig, cacheNames); } } } }
使用:
拿登录来说
public class LoginViewModel : BindableBase { private UserInfo userInfoModel; public UserInfo UserInfoModel { get { return userInfoModel; } set { userInfoModel = value; RaisePropertyChanged(); } } private bool isRemember; /// <summary> /// 是否记住密码 /// </summary> public bool IsRemember { get { return isRemember; } set { isRemember = value; RaisePropertyChanged(); } } private bool isAutoLogin; /// <summary> /// 是否自动登录 /// </summary> public bool IsAutoLogin { get { return isAutoLogin; } set { isAutoLogin = value; RaisePropertyChanged(); } } private ICacheManager _CacheManager { get; } public IRegionManager _regionManager { get; private set; } public IEventAggregator _eventAggregator { get; private set; } public ICacheHelper _cacheHelper { get; private set; }//缓存 public IUserInfoService _userInfoService { get; private set; } public DelegateCommand LoginCommand { get; private set; } public LoginViewModel(IRegionManager regionManager, IEventAggregator eventAggregator, ICacheHelper cacheHelper, IUserInfoService userInfoService, ICacheManager cacheManager) { UserInfoModel = new UserInfo(); _regionManager = regionManager; _eventAggregator = eventAggregator; _cacheHelper = cacheHelper; _userInfoService = userInfoService; _cacheHelper = new MemoryCacheHelper(); _CacheManager = cacheManager; LoginCommand = new DelegateCommand(UserLogin); LoadUserCache(); //是否自动登录 Task.Delay(2000).ContinueWith(t => { //如果自动登录 if (IsAutoLogin) { LoginCommand.Execute();//执行登录 } }); } private void UserLogin() { if (string.IsNullOrEmpty(UserInfoModel.UserName) || string.IsNullOrEmpty(UserInfoModel.PassWord)) return; //如果记住密码 if (IsRemember) { _CacheManager.Set(CacheKey.User, UserInfoModel);//写入缓存 } else { _CacheManager.Delete(CacheKey.User);//删除缓存 } _CacheManager.Set(CacheKey.IsRemember, IsRemember);//记住密码写入缓存 _CacheManager.Set(CacheKey.IsAutoLogin, IsAutoLogin);//自动登录写入缓存 if (UserInfoModel.UserName == "老六" && UserInfoModel.PassWord == "123456") { //UserInfoModel.PassWord = UserInfoModel.PassWord.GetMD5(); //var resu = _userInfoService.Login(UserInfoModel); //if (resu.Code == MyResponseCode.Success) //{ // var userInfo = JsonConvert.DeserializeObject<UserInfo>(resu.Data.ToString()); // _cacheHelper.Set<string>("token", userInfo.Remark);//token存到缓存中 // _eventAggregator.SendMessager(ViewNames.LoginView, "登入成功");//发布 //} //else //{ // PopupBox.Show("登录失败,API接口返回失败"); //} _eventAggregator.SendMessager(ViewNames.LoginView, "登入成功");//发布 } else { PopupBox.Show("用户名或密码错误"); } } /// <summary> /// 获取用户缓存 /// </summary> private void LoadUserCache() { if (_CacheManager.Get(CacheKey.User, out UserInfo user)) { UserInfoModel.UserName = user.UserName; UserInfoModel.PassWord = user.PassWord; } if (_CacheManager.Get(CacheKey.IsRemember, out bool isRemember)) { IsRemember = isRemember; } if (_CacheManager.Get(CacheKey.IsAutoLogin, out bool isAutoLogin)) { IsAutoLogin = isAutoLogin; } } }