bool IComponentContainer.InitializeObject(object objectInstance) { if (objectInstance == null) { throw new ArgumentNullException("objectInstance"); } Type objectType = objectInstance.GetType(); PropertyInfo[] properties = objectType.GetProperties(BindingFlags.Public | BindingFlags.Instance); if ((properties == null) || (properties.Length == 0)) { return(true); } foreach (PropertyInfo pi in properties) { if (pi.GetSetMethod() == null) { continue; } object[] attrs = pi.GetCustomAttributes(typeof(DependencyAttribute), /* inherit */ true); if ((attrs == null) || (attrs.Length == 0)) { continue; } object propertyValue = ((IComponentContainer)this).GetObject(pi.PropertyType); if (propertyValue != null) { pi.SetValue(objectInstance, propertyValue, null); } else { DependencyAttribute dependency = (DependencyAttribute)attrs[0]; if (dependency.Optional == false) { return(false); } } } return(true); }
private object CreateObject(Type objectType) { ConstructorInfo[] ctors = objectType.GetConstructors(); if ((ctors == null) || (ctors.Length == 0)) { return(null); } ConstructorInfo selectedCtor = null; for (int i = 0; i < ctors.Length; i++) { ConstructorInfo ci = ctors[i]; ParameterInfo[] parameters = ci.GetParameters(); object[] attrs = ci.GetCustomAttributes(typeof(DependencyAttribute), /* inherit */ false); if ((attrs != null) && (attrs.Length != 0)) { selectedCtor = ci; break; } if (selectedCtor == null) { selectedCtor = ci; } else if (selectedCtor.GetParameters().Length < parameters.Length) { selectedCtor = ci; } } if (selectedCtor != null) { ParameterInfo[] parameters = selectedCtor.GetParameters(); object[] paramValues = null; if (parameters.Length != 0) { paramValues = new object[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { object paramValue = GetObject(parameters[i].ParameterType); if (paramValue == null) { bool optional = false; object[] attrs = parameters[i].GetCustomAttributes(typeof(DependencyAttribute), /* inherit */ false); if ((attrs != null) && (attrs.Length != 0)) { DependencyAttribute dependency = (DependencyAttribute)attrs[0]; optional = dependency.Optional; } if (optional == false) { return(null); } } paramValues[i] = paramValue; } } return(selectedCtor.Invoke(paramValues)); } return(null); }