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;
        }
    }
}

源码下载

相关推荐
mudtools17 小时前
一份声明,多份产物:飞书 SDK 的 AI 工具面是怎么生成的
人工智能·.net·ai编程
云中飞鸿17 小时前
.Net和C#有什么关系?(从C++视角观察)
开发语言·c#·.net
2401_885885042 天前
国际语音C#接口怎么写?.NET环境下实现国际语音验证码批量下发
开发语言·c#·.net
1-1=02 天前
.NET Core 本地化 (L10n)
.net·.netcore
1-1=02 天前
.NET Core 健康检查
.net·.netcore·1024程序员节
波力海苔夹心脆6752 天前
C# string 字符串方法大全:判空、查找、截取、分割、替换一篇讲透
经验分享·c#·.net·字符串·string·入门教程
小羊没烦恼!2 天前
.NET无侵入自动化探针原理和主流实现
运维·开发语言·javascript·python·自动化·.net·1024程序员节
IT规划师2 天前
MQTT实战 - 遗嘱消息+心跳机制,让你的设备永远不会“假在线”(七)
物联网·.net
公子小六3 天前
基于.NET的Windows窗体编程之WinForms自定义控件(3)
windows·c#·.net·音视频·winforms