C#基於接口設計三層架構Unity篇

    1、引言

    面向接口(抽象)編程,是爲了下降程序的耦合度,符合依賴倒置原則。所以典型的三層架構UI、BLL、DAL基於接口設計後,會拓展成UI、IBLL、BLL、IDAL、DAL。在上一篇《C# IoC學習筆記》中咱們能夠了解到,控制反轉(IoC)使對象的建立交給了第三方IoC容器如Unity。利用Unity的IoC功能,能夠對基於接口設計的三層架構作進一步的升級,搭建一個更容易實現的可配置可擴展的三層架構;利用Unity的AOP功能,使框架更加的簡潔,由於它抽出了框架的公共邏輯部分。html

    2、項目創建

    2.一、項目創建編程

    依次新建項目UI(Client)、IBLL、BLL、IDAL、DAL、Model、Common。緩存

    2.2項目說明架構

    3、項目之間的引用關係

    3.一、對着項目名稱右鍵->添加->引用->項目,添加各個項目的引用。app

    3.二、引用說明框架

    4、項目需安裝的NuGet包

 

     5、注意事項

    對Unity容器的IoC調用進行封裝,Container應封裝成單例模式以提升效率,此處使用MemoryCache。ide

    5.一、在Common項目引用System.Runtime.Caching.dll,並在Helper文件夾下新建一個緩存幫助類:MemoryCacheHelper.cs。post

    /// <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.二、在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

 

    源碼下載atom

相關文章
相關標籤/搜索