IOC、DI<3> IServiceConllection 自定义IOC含属性注入、多实现注入,方法注入



csharp 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace IOC.Common
{
    public class ZenServiceCollection : IZenServiceCollection
    {
        // 记录IOC注册的抽象、实现
        private Dictionary<string, Type> zenRelationship = new Dictionary<string, Type>();
        /// <summary>
        /// IOC容器映射关系注册   ===》  抽象 和具体
        /// </summary>
        /// <param name="serviceType">具体类</param>
        /// <param name="implementtationType">实现类</param>
        public void AddTransient(Type serviceType, Type implementtationType)
        {
            this.zenRelationship.Add(serviceType.FullName, implementtationType);
        }
        /// <summary>
        /// 获取服务
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T GetService<T>()
        {
            {
                //只限有无参构造函数, 若类没有构造函数,ctr会自动生成一个无参构造函数,但若定义了有参构造函数,就不会自动创建无参构造函数啦
                //Type t = zenRelationship[typeof(T).FullName];
                //return (T)Activator.CreateInstance(t);
            }
            {
                继续迭代 支持有参构造函数 ,只支持1个层级的有参构造函数  
                //Type t = zenRelationship[typeof(T).FullName];
                确定构造当前对象使用哪个构造函数(默认选择参数最多的构造函数)
                //ConstructorInfo[] ctors = t.GetConstructors();
                //ConstructorInfo ctor = ctors.OrderByDescending(c => c.GetParameters().Length).FirstOrDefault();
                //List<object> paralist = new List<object>();
                //foreach (ParameterInfo item in ctor.GetParameters())
                //{
                //    Type tt = item.ParameterType;
                //    Type ttt = item.GetType();
                //    Type t1 = zenRelationship[item.ParameterType.FullName];
                //    var target = Activator.CreateInstance(t1);
                //    paralist.Add(target);
                //}
                //return (T)Activator.CreateInstance(t, paralist.ToArray());
            }
            {
                继续迭代 支持有参构造函数   无线层级的
                //Type t = zenRelationship[typeof(T).FullName];
                //return (T)this.GetService(t);               
            }
            {
                //利用特性 指明构造函数创建  ,  默认是  使用 参数最多
                Type t = zenRelationship[typeof(T).FullName];
                return (T)this.GetService(t);
            }
        }

        private object GetService(Type type)
        {
            #region 构造函数注入
            ConstructorInfo[] ctors = type.GetConstructors();
            ConstructorInfo ctor = ctors.Where(c=>c.IsDefined(typeof(SelectConstructAttribute),true)).FirstOrDefault();
            if (ctor==null)
            {
                //当ctor不存在,则表示 构造函数没有对应特性标识
                ctor= ctors.OrderByDescending(c => c.GetParameters().Length).FirstOrDefault();
            }
            List<object> paralist = new List<object>();            
            foreach (ParameterInfo item in ctor.GetParameters())
            {
                Type t1 = zenRelationship[item.ParameterType.FullName];
                var target=this.GetService(t1);               
                paralist.Add(target);
            }
            #region  方法注入
            //构造对象
            object objInstance = Activator.CreateInstance(type, paralist.ToArray());           
            //获取对象的属性  只获取含有特性PropertyInjectionAttribute的属性
            foreach (MethodInfo item in type.GetMethods().Where(c => c.IsDefined(typeof(MethodInjectionAttribute), true)))
            {
                List<object> paraOfMethodlist = new List<object>();
                foreach (ParameterInfo para in item.GetParameters())
                {
                    Type t1 = zenRelationship[para.ParameterType.FullName];
                    var target = this.GetService(t1);
                    paraOfMethodlist.Add(target);
                }
                item.Invoke(objInstance, paraOfMethodlist.ToArray());
            }
            #endregion
            #endregion
            #region  属性注入           
            //获取对象的属性  只获取含有特性PropertyInjectionAttribute的属性
            foreach (PropertyInfo item in type.GetProperties().Where(c=>c.IsDefined(typeof(PropertyInjectionAttribute),true)))
            {
                Type t1 = zenRelationship[item.PropertyType.FullName];
                var target = this.GetService(t1);
                item.SetValue(objInstance,target);
            }
            #endregion
            return objInstance;
        }
    }
}

源码下载

相关推荐
风云7 小时前
从 NLite 到 Vane.Container 1.0:压箱十六年的自研 DI 容器开源
.net·di·mini 容器·nlite
Jeff-Tsai14 小时前
Day 21:业务逻辑定制与 Plugin 的四个时点
.net·架构设计·erp·definition-driven
IT规划师15 小时前
Redis 核心机制 | 键生命周期与 TTL 管理
redis·.net
Jeff-Tsai2 天前
Day 20:多语言定制与资源结构
.net·架构设计·erp·definition-driven
Jeff-Tsai3 天前
Day 19:定制层的范围与叠加粒度
.net·架构设计·erp·definition-driven
Jeff-Tsai4 天前
Day 18:错误契约与用户可见消息
.net·架构设计·erp·definition-driven
IT规划师4 天前
HybridCache-缓存架构决策框架落地
架构·.net
Jeff-Tsai5 天前
Day 17:Connector 与调用端的职责收敛
.net·架构设计·erp·definition-driven
IT规划师5 天前
NET10 高并发架构契约与落地实现
架构·.net
公子小六6 天前
基于.NET的Windows窗体编程之WinForms数据持久化(1)
windows·microsoft·c#·.net·winforms