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

源码下载

相关推荐
非酋讨厌10 小时前
.NET 11 Preview 4 正式发布:Runtime-Async 全面启用、Process API 大幅扩展
.net
天天代码码天天19 小时前
工控机还是 Win7?我把 PP-OCRv6 做成了 14MB 纯 CPU DLL,.NET 3.5 也能直接调用
.net·win7·pp-ocrv6
找死的豆腐19 小时前
基于.NET的Windows窗体编程之WinForms图像控件
windows·.net
sdghterhd1 天前
当 GIS 开发遇上 .NET:一个 GDAL 集成工具库的架构设计与实践
.net
mudtools1 天前
HttpUtils:一个编译时生成的声明式 HTTP 客户端框架
网络·网络协议·http·.net
冰可乐配1 天前
OpenClaw.NET .NET 原生插件开发完全指南:以 Mempalace 插件为范例
.net
财财源源1 天前
.NET 程序保护实战系列01-流水线架构与保护引擎总览
架构·.net
牧濑红莉1 天前
自定义 Visual Studio 的界面外观
.net
淡淡的幼稚2 天前
【YFIOs】从传感芯片到表格曲线
uni-app·.net
精神底层2 天前
Skill——提示词的系统化封装
windows·.net