设为首页 加入收藏

TOP

设计一下类似SpringIoC的注入工具~Lind.DI(二)
2019-09-17 19:07:06 】 浏览:65
Tags:设计 类似 SpringIoC 注入 工具 Lind.DI
h (var type in arr) { try { if (type.GetCustomAttributes(false).Select(i => i.GetType()).Contains(typeof(ComponentAttribute))) { ComponentAttribute componentAttribute = (ComponentAttribute)type.GetCustomAttributes(false).FirstOrDefault(o => o.GetType() == typeof(ComponentAttribute)); if (type.GetInterfaces() != null && type.GetInterfaces().Any()) { type.GetInterfaces().ToList().ForEach(o => { registor(builder, type, o, componentAttribute); }); } else { registor(builder, type, type, componentAttribute); } } } catch (Exception) { throw new Exception($"Lind.DI init {type.Name} error."); } } container = builder.Build(); } /// <summary> /// 注册组件. /// </summary> /// <param name="builder">Builder.</param> /// <param name="typeImpl">Type impl.</param> /// <param name="type">Type.</param> /// <param name="componentAttribute">Component attribute.</param> static void registor(ContainerBuilder builder, Type typeImpl, Type type, ComponentAttribute componentAttribute) { if (componentAttribute.LifeCycle == LifeCycle.Global) { if (componentAttribute.Named != null) builder.RegisterType(typeImpl).Named(componentAttribute.Named, type).SingleInstance(); else builder.RegisterType(typeImpl).As(type).SingleInstance(); } else if (componentAttribute.LifeCycle == LifeCycle.CurrentScope) { if (componentAttribute.Named != null) builder.RegisterType(typeImpl).Named(componentAttribute.Named, type).InstancePerLifetimeScope(); else builder.RegisterType(typeImpl).As(type).InstancePerLifetimeScope(); } else { if (componentAttribute.Named != null) builder.RegisterType(typeImpl).Named(componentAttribute.Named, type).InstancePerRequest(); else builder.RegisterType(typeImpl).As(type).InstancePerRequest(); } } }

使用灵活方便

支持对象与对象之间的依赖

   [Component(Named="RunPeople")]
    public class RunPeople : IRun
    {
        public void Do()
        {
            System.Console.WriteLine("人类跑起来!");
        }
    }
    [Component]
    public class Fly
    {
        [Injection(Named="RunPeople")]
        Run run;
        public void step1()
        {
            run.Do();
            System.Console.WriteLine("飞行第一步!");
        }
    }

使用方式,程序入口先初始化DIFactory.Init();

       [Injection]
        Fly flyObj;
        void print(){
            DIFactory.Init();
            DIFactory.InjectFromObject(this);
            flyObj.step1();
        }
        static void Main(string[] args)
        {
            DIFactory.Init();
            System.Console.WriteLine("Hello World!");
            new Program().print();
        }

结果

Hello World!
人类跑起来!
飞行第一步!
首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇C# ASP.NET MVC:使用Cookie记住账.. 下一篇MyDAL - .UpdateAsync() 之 .SetS..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目