/// <summary> /// 属性注入 /// </summary> /// <param name="type"></param> /// <returns></returns> private object InjectPropertyFromCollection(object instance, Type type) { var properties = type.GetProperties(); int valuetypeIndex = 0; for (int i = 0; i < properties.Length; i++) { var item = properties[i]; if (!item.CanWrite) { continue; } if (item.PropertyType.IsValueType || item.PropertyType == TypeConst.StringType) { //值类型的和字符串注入 if (!(Parameters == null || Parameters.Length == 0 || valuetypeIndex >= Parameters.Length)) { //安装顺序配置输入参数 item.SetValue(instance, Parameters[valuetypeIndex]); valuetypeIndex++; } } else { if (item.GetValue(instance) == null) { //如果是类,则寻找容器里已经注册了的类型,没有则返回null var interFaceAndAbstractInstance = TypeItemObjectCollectionObject.GetValue(item.PropertyType); if (interFaceAndAbstractInstance != null) { item.SetValue(instance, interFaceAndAbstractInstance.ImplementationTypeInstance); } } } } return(instance); }
/// <summary> /// 获取实例(构造函数创建方式) /// </summary> /// <param name="type"></param> /// <returns></returns> private object GetInstance(Type type) { ConstructorInfo constructorInfo = null; var constructors = type.GetConstructors(); //判断构造函数的个数 if (constructors.Length == 1) { constructorInfo = constructors[0]; } else { Type iocDefaultAttributeType = typeof(IocDefaultAttribute); int count = 0; foreach (var item in constructors) { if (item.IsDefined(iocDefaultAttributeType)) { count++; constructorInfo = item; } } if (count == 0) { //如果有多个构造函数,但是没有标记。则取第一个构造函数 constructorInfo = constructors[0]; } else if (count != 1) { throw new Exception("有多个构造函数标记了IocDefault,或者没有标记IocDefault,会导致容器调用构造函数不明确"); } } var res = constructorInfo.GetParameters(); if (res.Length <= 0) { return(Activator.CreateInstance(type)); } //构造函数的参数注入 object[] paramsObjects = new object[res.Length]; int valuetypeIndex = 0; for (int i = 0; i < res.Length; i++) { var tmp = res[i]; if (tmp.ParameterType.IsValueType || tmp.ParameterType == TypeConst.StringType) { //值类型的和字符串注入 if (Parameters == null || Parameters.Length == 0 || valuetypeIndex >= Parameters.Length) { //没有配置输入参数,给予默认值 if (tmp.ParameterType.IsValueType) { paramsObjects[i] = 0; } } else { //安装顺序配置输入参数 paramsObjects[i] = Parameters[valuetypeIndex]; valuetypeIndex++; } } else { //如果是类,则寻找容器里已经注册了的类型,没有则返回null var interFaceAndAbstractInstance = TypeItemObjectCollectionObject.GetValue(tmp.ParameterType); if (interFaceAndAbstractInstance != null) { paramsObjects[i] = interFaceAndAbstractInstance.ImplementationTypeInstance; } } } return(Activator.CreateInstance(type, paramsObjects)); }