Unity的動態加載簡單使用

Unity的動態加載簡單使用
Unity能夠快速,輕量化的實現IOC,不用自已寫相似反射代碼來動態加載類或dll了
使用Unity先要用nuget獲取相關引用文件
Unity可經過代碼或config文件來配置要加動態加載的內容ide

使用示例函數

        static void Main(string[] args)
        {
            Console.WriteLine("'Y' use Config Register Type,Otherwise use Code Register Type");
            bool isUseConfig = Console.ReadLine().ToUpper().Equals("Y");

            IUnityContainer container = new UnityContainer();//定義ioc容器

            if (isUseConfig)
            {
                //經過Config來註冊Type
                UnityConfigurationSection configuration = (UnityConfigurationSection)ConfigurationManager.GetSection(UnityConfigurationSection.SectionName);
                configuration.Configure(container, "defaultContainer");//defaultContainer爲在config中定義的IOC容器名稱
            }
            else
            {
                //經過代碼來註冊Type
                CodeReg(container);
            }

            A a = container.Resolve<IA>() as A;//演示動態構造對像
            B b = container.Resolve<IB>() as B;

            var list = new ParameterOverrides();
            list.Add("name", "TomMao");//構造函數的參數名,參數值
            IE e = container.Resolve<IE>("e",list);//演示構造函數傳參 構造對像
            e.ShowName();
            e = container.Resolve<IE>("ee", list);//演示經過ioc不一樣名字,用不一樣的class構造同一接口對像,ee,e便是不一樣的ioc名字,表明使用不一樣的class,在註冊時加上ioc名字
            e.ShowName();

            if (null != a)
            {
                Console.WriteLine("a.B == null ? {0}", a.B == null ? "Yes" : "No");
                Console.WriteLine("a.C == null ? {0}", a.C == null ? "Yes" : "No");
                Console.WriteLine("a.D == null ? {0}", a.D == null ? "Yes" : "No");
            }
            Console.ReadLine();
        }

 

使用代碼配置加載項spa

        //經過代碼來實現Ioc容器的Type註冊
        private static void CodeReg(IUnityContainer container)
        {
            container.RegisterType(typeof(IA), Type.GetType("UnityDemo.A"));
            container.RegisterType(typeof(IB), Type.GetType("UnityDemo.B"));
            container.RegisterType(typeof(IC), Type.GetType("UnityDemo.C"));
            container.RegisterType(typeof(ID), Type.GetType("UnityDemo.D"));
            container.RegisterType(typeof(IE), Type.GetType("UnityDemo.E"), "e");//加入註冊的別名,可經過此名稱實現同一接口,不一樣實現
            container.RegisterType(typeof(IE), Type.GetType("UnityDemo.EE"), "ee");
        }

使用Config配置加載項code

相關文章
相關標籤/搜索