コード例 #1
0
        /// <summary>
        /// 递归
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        private object ResolveObject(Type t, string shortName = "")
        {
            string key  = GetKey(t.FullName, shortName);
            Type   type = dic[key];

            #region  择合适的构造函数

            /*有些类的构造函数有多个,这个时候就要选择一个进行了,
             * 像Core内置的ServiceCollection容器,他是根据并集原则,就是选择参数类别比较多的,用这个构造函数进行构造;
             * 市场上主流的第三方的容器是先找打标记的,没有的话找参数最多的构造函数
             */
            // var constructors = type.GetConstructors()[0];//简单点,找第一个

            /*我们找打了WcsConstructorAttribute标记的,没有的话找参数最多的*/

            ConstructorInfo constructor = null;
            constructor = type.GetConstructors().FirstOrDefault(f => f.IsDefined(typeof(WcsConstructorAttribute), true));
            if (constructor == null)
            {
                constructor = type.GetConstructors().OrderByDescending(f => f.GetParameters().Length).FirstOrDefault();
            }
            #endregion

            #region 因为构造的时候,可能构造函数有参数,所以要准备参数,然后传入
            List <object> paraList = new List <object>();
            foreach (var para in constructor.GetParameters())
            {
                Type paraType = para.ParameterType;//获取参数的类别,IUserDAL
                //string paraKey = paraType.FullName;//IUserDAL的完整名称
                //Type paraTargeType = dic[paraKey]; //UserDAL
                //paraList.Add(Activator.CreateInstance(paraTargeType));

                //单接口多实现,构造所需要的参数时实例化时是否需要选择构造哪个实例
                string paraShortName = GetShortName(para);

                object paraObj = this.ResolveObject(paraType, paraShortName);
                paraList.Add(paraObj);
            }
            #endregion

            object instance = Activator.CreateInstance(type, paraList.ToArray());

            #region 属性注入

            /*思路:
             * 找出构造出的对象的属性,构造属性,然后对其属性赋值,
             * 我们就只找打了WcsPropertyAttribute特性的属性
             */
            foreach (var prop in type.GetProperties().Where(p => p.IsDefined(typeof(WcsPropertyAttribute), true)))
            {
                Type   propertyType     = prop.PropertyType;
                object propertyInstance = ResolveObject(propertyType);
                prop.SetValue(instance, propertyInstance);
            }
            #endregion

            #region 方法注入
            /*找打了WcsMethodAttribute的方法,对他的参数进行构造*/
            foreach (var method in type.GetMethods().Where(p => p.IsDefined(typeof(WcsMethodAttribute), true)))
            {
                List <object> methodParaList = new List <object>();
                foreach (var para in method.GetParameters())
                {
                    Type   paraType = para.ParameterType;
                    object paraObj  = this.ResolveObject(paraType);
                    methodParaList.Add(paraObj);
                }
                method.Invoke(instance, methodParaList.ToArray());
            }
            #endregion

            // return instance;
            return(instance.AOP(t));
        }
コード例 #2
0
        /// <summary>
        /// 创建实例
        /// </summary>
        /// <param name="abstractType">抽象接口的Type</param>
        /// <param name="shortName">具体实现类的shortName</param>
        /// <returns></returns>
        private object ResolveObject(Type abstractType, string shortName = null)
        {
            string key = this.GetKey(abstractType.FullName, shortName);
            var    containerRegistModel = this.ContainerDictionary[key];
            Type   type = containerRegistModel.TargetType;

            #region 生命周期管理
            switch (containerRegistModel.LifeTime)
            {
            case LifeTimeType.Transient:
                Console.WriteLine("do nothing before");
                break;

            case LifeTimeType.Singleton:
                if (containerRegistModel.SingletonInstance == null)
                {
                    break;
                }
                else
                {
                    return(containerRegistModel.SingletonInstance);
                }

            case LifeTimeType.Scope:
                if (this.ScopeDictionaty.ContainsKey(key))
                {
                    return(this.ScopeDictionaty[key]);
                }
                else
                {
                    break;
                }

            case LifeTimeType.PerThread:
                object threadObj = CusCallContext.GetData($"{key}{Thread.CurrentThread.ManagedThreadId}");
                if (threadObj == null)
                {
                    break;
                }
                else
                {
                    return(threadObj);
                }

            default:
                break;
            }
            #endregion

            #region  择合适的构造函数
            ConstructorInfo ctor = null;
            // 1 标记特性优先
            ctor = type.GetConstructors().FirstOrDefault(c => c.IsDefined(typeof(ConstructorInjectionAttribute), true));
            if (ctor == null)
            {
                // 2 参数个数最多
                ctor = type.GetConstructors().OrderByDescending(c => c.GetParameters().Length).First();
            }
            #endregion

            #region 准备构造函数的参数
            List <object> paraList     = new List <object>();
            object[]      paraConstant = this.ParaListDictionary.ContainsKey(key) ? this.ParaListDictionary[key] : null;
            int           idx          = 0;
            int           parameterLen = ctor.GetParameters().Where(c => c.IsDefined(typeof(ParameterConstantAttribute), true)).Count();
            if (paraConstant != null && paraConstant.Length != parameterLen)
            {
                // 传入的常量参数值与定义的常量参数个数不一致
                throw new Exception(message: $"传入的常量参数值个数与定义的常量参数个数不一致@{key}");
            }

            foreach (var para in ctor.GetParameters())
            {
                Type paraType = para.ParameterType;//获取参数的类型
                if (para.IsDefined(typeof(ParameterConstantAttribute), true))
                {
                    object objItem     = paraConstant[idx];
                    Type   objItemType = objItem.GetType();
                    if (paraType != objItemType)
                    {
                        //传入的参数值类型与定义的参数类型不一致
                        throw new Exception("传入的参数值类型与定义的参数类型不一致");
                    }
                    paraList.Add(objItem);
                    idx++;
                }
                else
                {
                    string paraShortName = this.GetShortName(para);
                    object paraInstance  = this.ResolveObject(paraType, paraShortName);
                    paraList.Add(paraInstance);
                }
            }
            object oInstance = Activator.CreateInstance(type, paraList.ToArray());
            #endregion


            #region 属性注入
            foreach (var prop in type.GetProperties().Where(p => p.IsDefined(typeof(PropertyInjectionAttribute), true)))
            {
                Type   propType     = prop.PropertyType;
                object propInstance = this.ResolveObject(propType, this.GetShortName(prop));
                prop.SetValue(oInstance, propInstance);
            }
            #endregion

            #region 方法注入
            foreach (var method in type.GetMethods().Where(p => p.IsDefined(typeof(MethodInjectionAttribute), true)))
            {
                List <object> methodParaList = new List <object>();
                foreach (var methodPara in method.GetParameters())
                {
                    Type   methodParaType     = methodPara.ParameterType;//获取方法的参数类型
                    object methodParaInstance = this.ResolveObject(methodParaType);
                    methodParaList.Add(methodParaInstance);
                }
                method.Invoke(oInstance, methodParaList.ToArray());
            }
            #endregion

            #region 生命周期管理
            switch (containerRegistModel.LifeTime)
            {
            case LifeTimeType.Transient:
                Console.WriteLine("do nothing after");
                break;

            case LifeTimeType.Singleton:
                containerRegistModel.SingletonInstance = oInstance;
                break;

            case LifeTimeType.Scope:
                this.ScopeDictionaty[key] = oInstance;
                break;

            case LifeTimeType.PerThread:
                CusCallContext.SetData($"{key}{Thread.CurrentThread.ManagedThreadId}", oInstance);
                break;

            default:
                break;
            }
            #endregion

            return(oInstance.AOP(abstractType));
        }
コード例 #3
0
        /// <summary>
        /// 递归实现多层级构造
        /// </summary>
        /// <typeparam name="TFrom"></typeparam>
        /// <returns></returns>
        private object ResolveObject(Type abstractType, string shortName = null, LifetimeType lifetimeType = LifetimeType.Transient)
        {
            string key   = this.GetKey(abstractType.FullName, shortName); //abstractType.FullName;
            var    model = this.MJDContainerDictionary[key];

            #region 生命周期管理
            switch (model.Lifetime)
            {
            case LifetimeType.Transient:
                Console.WriteLine("nothing");
                break;

            case LifetimeType.Singleton:
                if (model.SingletonIntance == null)
                {
                    break;
                }
                else
                {
                    return(model.SingletonIntance);
                }

            case LifetimeType.Scope:
                if (this.MJDContainerScopDictionary.ContainsKey(key))
                {
                    return(this.MJDContainerScopDictionary[key]);
                }
                else
                {
                    break;
                }

            default:
                break;
            }
            #endregion
            Type type = model.TargetType;
            #region  择合适的参数
            ConstructorInfo ctor = null;
            //标记特性
            ctor = type.GetConstructors().FirstOrDefault(c => c.IsDefined(typeof(MJDContainerAttribute), true));
            if (ctor == null)
            {
                //参数个数最多
                ctor = type.GetConstructors().OrderByDescending(c => c.GetParameters().Length).First();
            }
            //  var ctor = type.GetConstructors()[0];
            #endregion
            #region 准备构造函数参数

            List <object> paraList = new List <object>();

            object[] paraConstant = MJDContainerValueDictionary.ContainsKey(key) ? MJDContainerValueDictionary[key] : null;
            int      iIndex       = 0;
            foreach (var para in ctor.GetParameters())
            {
                if (para.IsDefined(typeof(MJDParameterConstantAttribute), true))
                {
                    paraList.Add(paraConstant[iIndex++]);
                }
                else
                {
                    Type paraType = para.ParameterType;
                    //string paraKey = paraType.FullName;
                    //Type paraTargetType = this.MJDContainerDictionary[paraKey];
                    //object paraInstance = Activator.CreateInstance(paraTargetType);
                    string paraShortName = GetShortName(para);
                    object paraInstance  = this.ResolveObject(paraType, paraShortName);
                    paraList.Add(paraInstance);
                }
            }
            #endregion

            object oInstance = Activator.CreateInstance(type, paraList.ToArray());

            #region 属性注入
            foreach (var prop in type.GetProperties().Where(p => p.IsDefined(typeof(MJDPropertyinjectionAttribute), true)))
            {
                Type   propType      = prop.PropertyType;
                string paraShortName = GetShortName(prop);
                object propInstance  = this.ResolveObject(propType, paraShortName);
                prop.SetValue(oInstance, propInstance);
            }
            #endregion

            #region 方法注入
            foreach (var method in type.GetMethods().Where(m => m.IsDefined(typeof(MJDMethodinjectionAttribute), true)))
            {
                List <object> paraInjectionList = new List <object>();
                foreach (var para in method.GetParameters())
                {
                    Type   paraType      = para.ParameterType;
                    string paraShortName = GetShortName(para);
                    object paraInstance  = this.ResolveObject(paraType, paraShortName);
                    paraInjectionList.Add(paraInstance);
                }
                method.Invoke(oInstance, paraInjectionList.ToArray());
            }
            #endregion

            #region 生命周期管理
            switch (model.Lifetime)
            {
            case LifetimeType.Transient:
                Console.WriteLine("nothing");
                break;

            case LifetimeType.Singleton:
                model.SingletonIntance = oInstance;
                break;

            case LifetimeType.Scope:
                this.MJDContainerScopDictionary[key] = oInstance;
                break;

            default:
                break;
            }
            #endregion
            return(oInstance.AOP(abstractType));
            //  return oInstance;
        }
コード例 #4
0
        /// <summary>
        /// 递归--可以完成不限层级的东西
        /// </summary>
        /// <typeparam name="TFrom"></typeparam>
        /// <returns></returns>
        private object ResolveObject(Type abstractType, string shortName = null)
        {
            string key   = this.GetKey(abstractType.FullName, shortName);
            var    model = this.ZhaoxiContainerDictionary[key];

            #region 检测生命周期
            switch (model.Lifetime)
            {
            case LifetimeType.Transient:
                Console.WriteLine("Transient Do Nothing Before...");
                break;

            case LifetimeType.Singleton:
                if (model.SingletonInstance == null)
                {
                    break;
                }
                else
                {
                    return(model.SingletonInstance);
                }

            case LifetimeType.Scope:
                if (this.ZhaoxiContainerScopeDictionary.ContainsKey(key))
                {
                    return(this.ZhaoxiContainerScopeDictionary[key]);
                }
                else
                {
                    break;
                }

            case LifetimeType.PerThread:
                object oValue = CustomCallContext <object> .GetData($"{key}{Thread.CurrentThread.ManagedThreadId}");

                if (oValue == null)
                {
                    break;
                }
                else
                {
                    return(oValue);
                }

            default:
                break;
            }
            #endregion
            Type type = model.TargetType;

            #region  择合适的构造函数
            ConstructorInfo ctor = null;

            //2.选择特性标记的,如果没有则去选择参数最多的
            ctor = type.GetConstructors().FirstOrDefault(c => c.IsDefined(typeof(ZhaoxiConstructorAttribute), true));
            if (ctor == null)
            {
                //1.参数个数最多的
                ctor = type.GetConstructors().OrderByDescending(c => c.GetParameters().Length).First();//参数最多的
            }
            #endregion


            #region 准备构造函数的参数
            List <object> paraList = new List <object>();

            object[] paraConstant = this.ZhaoxiContainerValueDictionary.ContainsKey(key) ? this.ZhaoxiContainerValueDictionary[key]:null;

            int iIndex = 0;
            foreach (var para in ctor.GetParameters())//获取构造函数的参数
            {
                if (para.IsDefined(typeof(ZhaoxiParameterConstantAttribute), true))
                {
                    paraList.Add(paraConstant[iIndex]);
                    iIndex++;
                }
                else
                {
                    Type   paraType      = para.ParameterType;//获取参数的类型 项目中是
                    string paraShortName = this.GetShortName(para);

                    object paraInstance = this.ResolveObject(paraType, paraShortName);
                    paraList.Add(paraInstance);//创建目标类型实例
                }
            }

            #endregion
            object oInstance = Activator.CreateInstance(type, paraList.ToArray());

            #region 属性注入
            foreach (var prop in type.GetProperties().Where(p => p.IsDefined(typeof(ZhaoxiPropertyInjectAttribute), true)))
            {
                Type propType = prop.PropertyType;

                string propShortName = this.GetShortName(prop);

                object propInstance = this.ResolveObject(propType, propShortName);
                prop.SetValue(oInstance, propInstance);
            }
            #endregion

            #region 方法注入
            foreach (var meth in type.GetMethods().Where(m => m.IsDefined(typeof(ZhaoxiMethodAttribute), true)))
            {
                List <object> methParaList = new List <object>();

                //object[] methParaConstant = this.ZhaoxiContainerValueDictionary.ContainsKey(key) ? this.ZhaoxiContainerValueDictionary[key] : null;

                foreach (var methPara in meth.GetParameters())//获取函数的参数
                {
                    //if (methPara.IsDefined(typeof(ZhaoxiParameterConstantAttribute), true))
                    //{
                    //    methParaList.Add(paraConstant[iIndex]);
                    //    iIndex++;
                    //}
                    //else
                    {
                        Type   methParaType     = methPara.ParameterType;//获取参数的类型
                        string paraShortName    = this.GetShortName(methPara);
                        object methParaInstance = this.ResolveObject(methParaType, paraShortName);
                        methParaList.Add(methParaInstance);//创建目标类型实例
                    }
                }
                meth.Invoke(oInstance, methParaList.ToArray());
            }
            #endregion

            #region Lifetime
            switch (model.Lifetime)
            {
            case LifetimeType.Transient:
                Console.WriteLine("Transient Do Nothing After...");
                break;

            case LifetimeType.Singleton:
                model.SingletonInstance = oInstance;
                break;

            case LifetimeType.Scope:
                this.ZhaoxiContainerScopeDictionary[key] = oInstance;
                break;

            case LifetimeType.PerThread:
                CustomCallContext <object> .SetData($"{key}{Thread.CurrentThread .ManagedThreadId}", oInstance);

                break;

            default:
                break;
            }
            #endregion

            return(oInstance.AOP(abstractType));//整合AOP与IOC
            //return oInstance;
        }