Unity容器使用筆記

1、配置文件Unity容器使用筆記
說(shuō)明:此處有兩個(gè)容器的節(jié)點(diǎn),用來(lái)分別初始化兩個(gè)容器,可以應(yīng)對(duì)需要注入兩個(gè)dbContext的情況。
代碼:
<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Unity.Configuration"/>
</configSections>
<unity>
<sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Unity.Interception.Configuration"/>
<containers>
<container name="yydyoaSection">
<extension type="Interception"/>
<register type="Study.Unity.Interface.IDoWork,Study.Unity" mapTo=" Study.Unity.Service.StudentDoWork,Study.Unity">
<interceptor type="InterfaceInterceptor"/>
<interceptionBehavior type="Study.Unity.Aop.ParameterCheckBehavior,Study.Unity"/>
<interceptionBehavior type="Study.Unity.Aop.CachingBehavior,Study.Unity"/>
<interceptionBehavior type="Study.Unity.Aop.ExpessionBehavior,Study.Unity"/>
<interceptionBehavior type="Study.Unity.Aop.LogBeforeBehavior,Study.Unity"/>
</register>
</container>
<container name="managerSection">
<extension type="Interception"/>
<register type="Study.Unity.Interface.IDoWork,Study.Unity" mapTo=" Study.Unity.Service.TeacherDoWork,Study.Unity">
<interceptor type="InterfaceInterceptor"/>
</register>
</container>
</containers>
</unity>
</configuration>

創(chuàng)新互聯(lián)-專(zhuān)業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性?xún)r(jià)比酉陽(yáng)土家族苗族網(wǎng)站開(kāi)發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫(kù),直接使用。一站式酉陽(yáng)土家族苗族網(wǎng)站制作公司更省心,省錢(qián),快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋酉陽(yáng)土家族苗族地區(qū)。費(fèi)用合理售后完善,十多年實(shí)體公司更值得信賴(lài)。

2、初始化容器
說(shuō)明:創(chuàng)建了一個(gè)枚舉,用來(lái)對(duì)應(yīng)配置文件中的兩個(gè)節(jié)點(diǎn),然后通過(guò)擴(kuò)展方法獲取到枚舉值在配置文件中的節(jié)點(diǎn)名稱(chēng),用來(lái)分別初始化不同的容器。
代碼:
容器的工廠:

  public class DIFactory
    {
        private static readonly object _SyncHelper = new object();
        private static volatile Dictionary<EnContainer, IUnityContainer> _UnityContainerDictionary = new Dictionary<EnContainer, IUnityContainer>();

        public static IUnityContainer GetContainer(EnContainer enContainer)
        {
            if (!_UnityContainerDictionary.ContainsKey(enContainer))
            {
                lock (_SyncHelper)
                {
                    if (!_UnityContainerDictionary.ContainsKey(enContainer))
                    {
                        //配置UnityContainer
                        IUnityContainer container = new UnityContainer();
                        ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
                        fileMap.ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "CfgFiles\\Unity.Config");
                        Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
                        UnityConfigurationSection configSection = (UnityConfigurationSection)configuration.GetSection(UnityConfigurationSection.SectionName);
                        string strSection = enContainer.Speccn();
                        configSection.Configure(container, strSection);

                        _UnityContainerDictionary.Add(enContainer, container);
                    }
                }
            }
            return _UnityContainerDictionary[enContainer];
        }
    }
    枚舉:
 public enum EnContainer
    {
        [Speccn("yydyoaSection")]
        YYDYOA = 1,
        [Speccn("managerSection")]
        MANAGER = 2
    }
    特性:
     [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
    public class SpeccnAttribute : Attribute
    {
        private string Speccn { get; set; }
        public SpeccnAttribute(string speccn)
        {
            this.Speccn = speccn;
        }
        public string GetSpeccn()
        {
            return this.Speccn;
        }
    }
    擴(kuò)展方法:   
 public static class EnumExtend
    {
        public static string Speccn(this Enum enContainer)
        {
            Type type = enContainer.GetType();
            FieldInfo field = type.GetField(enContainer.ToString());
            if (field.IsDefined(typeof(SpeccnAttribute), true))
            {
                SpeccnAttribute speccnAttribute = (SpeccnAttribute)field.GetCustomAttribute(typeof(SpeccnAttribute));
                return speccnAttribute.GetSpeccn();
            }
            else
            {
                return enContainer.ToString();
            }
        }
    }

3、接口和實(shí)現(xiàn)類(lèi)的代碼
接口:

  public interface IDoWork
    {
        string Show(string arg);
    }
    實(shí)現(xiàn)類(lèi):
 public class StudentDoWork : IDoWork
    {
        public string Show(string arg)
        {
            Console.WriteLine($"{this.GetType().Name}_DoWork Before");
            Console.WriteLine($"{this.GetType().Name}_DoWork After");
            return nameof(StudentDoWork);
        }
    }

        public class TeacherDoWork : IDoWork
    {
        public string Show(string arg)
        {
            Console.WriteLine($"{this.GetType().Name}_DoWork");
            return nameof(TeacherDoWork);
        }
    }
    4、AOP擴(kuò)展類(lèi)的代碼:
        參數(shù)檢查:
          public class ParameterCheckBehavior : IInterceptionBehavior
    {
        public bool WillExecute => true;

        public IEnumerable<Type> GetRequiredInterfaces()
        {
            return Type.EmptyTypes;
        }

        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            Console.WriteLine("ParameterCheckBehavior");
            if (input.Inputs[0].ToString().Length < 10)//可以過(guò)濾一下敏感詞
            {
                //返回一個(gè)異常
                return input.CreateExceptionMethodReturn(new Exception("密碼長(zhǎng)度不能小于10位"));
            }
            else
            {
                Console.WriteLine("參數(shù)檢測(cè)無(wú)誤");
                return getNext().Invoke(input, getNext);
            }
        }
    }
    日志:
 public class LogBeforeBehavior : IInterceptionBehavior
    {
        public bool WillExecute => true;

        public IEnumerable<Type> GetRequiredInterfaces()
        {
            return Type.EmptyTypes;
        }

        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            Console.WriteLine("LogBehavior before");
            IMethodReturn method = getNext()(input, getNext);
            Console.WriteLine("LogBehavior after");
            return method;
        }
    }
    異常:
 public class ExpessionBehavior : IInterceptionBehavior
    {
        public bool WillExecute => true;

        public IEnumerable<Type> GetRequiredInterfaces()
        {
            return Type.EmptyTypes;
        }

        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            Console.WriteLine("ExpessionBehavior before");

            IMethodReturn method = getNext()(input, getNext);
            if (method.Exception != null)
                Console.WriteLine($"異常:{method.Exception.Message}");
            Console.WriteLine("ExpessionBehavior after");
            return method;
        }
    }
    緩存:
  public class CachingBehavior : IInterceptionBehavior
    {
        public IEnumerable<Type> GetRequiredInterfaces()
        {
            return Type.EmptyTypes;
        }

        private static Dictionary<string, object> CachingBehaviorDictionary = new Dictionary<string, object>();

        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            string key = $"{input.MethodBase.Name}_{Newtonsoft.Json.JsonConvert.SerializeObject(input.Inputs)}";
            if (CachingBehaviorDictionary.ContainsKey(key))
            {
                return input.CreateMethodReturn(CachingBehaviorDictionary[key]);
            }
            else
            {
                IMethodReturn result = getNext().Invoke(input, getNext);
                if (result.ReturnValue != null)
                {
                    CachingBehaviorDictionary.Add(key, result.ReturnValue);
                    Console.WriteLine("CachingBehavior");
                }
                return result;
            }
        }

        public bool WillExecute
        {
            get { return true; }
        }
    }
    5、測(cè)試代碼
 static void Main(string[] args)
        {
            IUnityContainer yydyoaContainer = DIFactory.GetContainer(EnContainer.YYDYOA);
            IDoWork doWork = yydyoaContainer.Resolve<IDoWork>();
            doWork.Show("12345678901234");
            yydyoaContainer = DIFactory.GetContainer(EnContainer.MANAGER);
            doWork = yydyoaContainer.Resolve<IDoWork>();
            doWork.Show("123");
            Console.ReadKey();
        }
    6、總結(jié)
        AOP擴(kuò)展的進(jìn)入順序是根據(jù)配置文件從上到下進(jìn)入,業(yè)務(wù)邏輯與拓展邏輯的執(zhí)行順序是根據(jù)getNext().Invoke(input, getNext)代碼的位置決定。

名稱(chēng)欄目:Unity容器使用筆記
標(biāo)題鏈接:http://bm7419.com/article34/jcegpe.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供電子商務(wù)、響應(yīng)式網(wǎng)站、自適應(yīng)網(wǎng)站、商城網(wǎng)站網(wǎng)站設(shè)計(jì)公司、建站公司

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

網(wǎng)站優(yōu)化排名