一、引言 面向介面(抽象)編程,是為了降低程式的耦合度,符合依賴倒置原則。因此典型的三層架構UI、BLL、DAL基於介面設計後,會拓展成UI、IBLL、BLL、IDAL、DAL。在上一篇《C# IoC學習筆記》中我們可以瞭解到,控制反轉(IoC)使對象的創建交給了第三方IoC容器如Unity。利用U ...
一、引言
面向介面(抽象)編程,是為了降低程式的耦合度,符合依賴倒置原則。因此典型的三層架構UI、BLL、DAL基於介面設計後,會拓展成UI、IBLL、BLL、IDAL、DAL。在上一篇《C# IoC學習筆記》中我們可以瞭解到,控制反轉(IoC)使對象的創建交給了第三方IoC容器如Unity。利用Unity的IoC功能,可以對基於介面設計的三層架構做進一步的升級,搭建一個更容易實現的可配置可擴展的三層架構;利用Unity的AOP功能,使框架更加的簡潔,因為它抽出了框架的公共邏輯部分。
二、項目建立
2.1、項目建立
依次新建項目UI(Client)、IBLL、BLL、IDAL、DAL、Model、Common。
2.2項目說明
三、項目之間的引用關係
3.1、對著項目名稱右鍵->添加->引用->項目,添加各個項目的引用。
3.2、引用說明
四、項目需安裝的NuGet包
五、註意事項
對Unity容器的IoC調用進行封裝,Container應封裝成單例模式以提高效率,此處使用MemoryCache。
5.1、在Common項目引用System.Runtime.Caching.dll,併在Helper文件夾下新建一個緩存幫助類:MemoryCacheHelper.cs。
/// <summary> /// 記憶體緩存幫助類,支持絕對過期時間、滑動過期時間、文件依賴三種緩存方式。 /// </summary> class MemoryCacheHelper { private static readonly object _locker1 = new object(), _locker2 = new object(); /// <summary> /// 取緩存項,如果不存在則返回空。 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <returns></returns> public static T GetCacheItem<T>(string key) { try { return (T)MemoryCache.Default[key]; } catch { return default(T); } } /// <summary> /// 是否包含指定鍵的緩存項 /// </summary> /// <param name="key"></param> /// <returns></returns> public static bool Contains(string key) { return MemoryCache.Default.Contains(key); } /// <summary> /// 取緩存項,如果不存在則新增緩存項。 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="cachePopulate"></param> /// <param name="slidingExpiration"></param> /// <param name="absoluteExpiration"></param> /// <returns></returns> public static T GetOrAddCacheItem<T>(string key, Func<T> cachePopulate, TimeSpan? slidingExpiration = null, DateTime? absoluteExpiration = null) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentException("Invalid cache key"); if (cachePopulate == null) throw new ArgumentNullException("cachePopulate"); if (slidingExpiration == null && absoluteExpiration == null) throw new ArgumentException("Either a sliding expiration or absolute must be provided"); if (MemoryCache.Default[key] == null) { lock (_locker1) { if (MemoryCache.Default[key] == null) { T cacheValue = cachePopulate(); if (!typeof(T).IsValueType && cacheValue == null) //如果是引用類型且為NULL則不存緩存 { return cacheValue; } var item = new CacheItem(key, cacheValue); var policy = CreatePolicy(slidingExpiration, absoluteExpiration); MemoryCache.Default.Add(item, policy); } } } return (T)MemoryCache.Default[key]; } /// <summary> /// 取緩存項,如果不存在則新增緩存項。 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="cachePopulate"></param> /// <param name="dependencyFilePath"></param> /// <returns></returns> public static T GetOrAddCacheItem<T>(string key, Func<T> cachePopulate, string dependencyFilePath) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentException("Invalid cache key"); if (cachePopulate == null) throw new ArgumentNullException("cachePopulate"); if (MemoryCache.Default[key] == null) { lock (_locker2) { if (MemoryCache.Default[key] == null) { T cacheValue = cachePopulate(); if (!typeof(T).IsValueType && cacheValue == null) //如果是引用類型且為NULL則不存緩存 { return cacheValue; } var item = new CacheItem(key, cacheValue); var policy = CreatePolicy(dependencyFilePath); MemoryCache.Default.Add(item, policy); } } } return (T)MemoryCache.Default[key]; } /// <summary> /// 指定緩存項的一組逐出和過期詳細信息 /// </summary> /// <param name="slidingExpiration"></param> /// <param name="absoluteExpiration"></param> /// <returns></returns> private static CacheItemPolicy CreatePolicy(TimeSpan? slidingExpiration, DateTime? absoluteExpiration) { var policy = new CacheItemPolicy(); if (absoluteExpiration.HasValue) { policy.AbsoluteExpiration = absoluteExpiration.Value; } else if (slidingExpiration.HasValue) { policy.SlidingExpiration = slidingExpiration.Value; } policy.Priority = CacheItemPriority.Default; return policy; } /// <summary> /// 指定緩存項的一組逐出和過期詳細信息 /// </summary> /// <param name="filePath"></param> /// <returns></returns> private static CacheItemPolicy CreatePolicy(string filePath) { CacheItemPolicy policy = new CacheItemPolicy(); policy.ChangeMonitors.Add(new HostFileChangeMonitor(new List<string>() { filePath })); policy.Priority = CacheItemPriority.Default; return policy; } /// <summary> /// 移除指定鍵的緩存項 /// </summary> /// <param name="key"></param> public static void RemoveCacheItem(string key) { if (Contains(key)) { MemoryCache.Default.Remove(key); } } }View Code
5.2、在Common項目Helper文件夾下麵新建一個Unity幫助類:UnityHelper.cs,並實現Container的緩存。
/// <summary> /// Unity容器幫助類 /// </summary> public static class UnityHelper { /// <summary> /// Unity容器創建對象(不含別名) /// </summary> /// <param name="containerName">容器名稱</param> /// <returns></returns> public static T GetObject<T>(string containerName) { IUnityContainer container = MemoryCacheHelper.GetOrAddCacheItem(containerName, () => { IUnityContainer unityContainer = new UnityContainer(); ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap { ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + @"ConfigFiles\Unity.config") }; Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); UnityConfigurationSection configSection = (UnityConfigurationSection)configuration.GetSection(UnityConfigurationSection.SectionName); configSection.Configure(unityContainer, containerName); return unityContainer; },TimeSpan.FromMinutes(30),null); return container.Resolve<T>(); } /// <summary> /// Unity容器創建對象(含別名) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="containerName">容器名稱</param> /// <param name="alisName">對象別名</param> /// <returns></returns> public static T GetObject<T>(string containerName, string alisName) { IUnityContainer container = MemoryCacheHelper.GetOrAddCacheItem(containerName, () => { IUnityContainer unityContainer = new UnityContainer(); ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap { ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + @"ConfigFiles\Unity.config") }; Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); UnityConfigurationSection configSection = (UnityConfigurationSection)configuration.GetSection(UnityConfigurationSection.SectionName); configSection.Configure(unityContainer, containerName); return unityContainer; }, TimeSpan.FromMinutes(30), null); return container.Resolve<T>(alisName); } }View Code