Unity容器使用筆記-創(chuàng)新互聯(lián)

1、配置文件Unity容器使用筆記
說明:此處有兩個(gè)容器的節(jié)點(diǎn),用來分別初始化兩個(gè)容器,可以應(yīng)對需要注入兩個(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)公司專業(yè)IDC數(shù)據(jù)服務(wù)器托管提供商,專業(yè)提供成都服務(wù)器托管,服務(wù)器租用,雅安機(jī)房托管,雅安機(jī)房托管,成都多線服務(wù)器托管等服務(wù)器托管服務(wù)。

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

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)類的代碼
接口:

public interface IDoWork
    {
        string Show(string arg);
    }
實(shí)現(xiàn)類:
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ò)展類的代碼:
        參數(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)//可以過濾一下敏感詞
            {
                //返回一個(gè)異常
                return input.CreateExceptionMethodReturn(new Exception("密碼長度不能小于10位"));
            }
            else
            {
                Console.WriteLine("參數(shù)檢測無誤");
                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、測試代碼
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)代碼的位置決定。

創(chuàng)新互聯(lián)www.cdcxhl.cn,專業(yè)提供香港、美國云服務(wù)器,動態(tài)BGP最優(yōu)骨干路由自動選擇,持續(xù)穩(wěn)定高效的網(wǎng)絡(luò)助力業(yè)務(wù)部署。公司持有工信部辦法的idc、isp許可證, 機(jī)房獨(dú)有T級流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確進(jìn)行流量調(diào)度,確保服務(wù)器高可用性。佳節(jié)活動現(xiàn)已開啟,新人活動云服務(wù)器買多久送多久。

分享名稱:Unity容器使用筆記-創(chuàng)新互聯(lián)
當(dāng)前網(wǎng)址:http://muchs.cn/article46/dpeihg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供商城網(wǎng)站靜態(tài)網(wǎng)站、自適應(yīng)網(wǎng)站網(wǎng)站設(shè)計(jì)公司、網(wǎng)站維護(hù)微信公眾號

廣告

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

成都定制網(wǎng)站網(wǎng)頁設(shè)計(jì)