private static object Create(Cat cat, Type type, Type[] genericArguments) { if (genericArguments.Length > 0) { type = type.MakeGenericType(genericArguments); } var constructors = type.GetConstructors(); if (constructors.Length == 0) { throw new InvalidOperationException($"Cannot create the instance of {type} which does not have an public constructor."); } var constructor = constructors.FirstOrDefault(it => it.GetCustomAttributes(false).OfType <InjectionAttribute>().Any()); constructor = constructor ?? constructors.First(); var parameters = constructor.GetParameters(); if (parameters.Length == 0) { return(Activator.CreateInstance(type)); } var arguments = new object[parameters.Length]; for (int index = 0; index < arguments.Length; index++) { var parameter = parameters[index]; var parameterType = parameter.ParameterType; if (cat.HasRegistry(parameterType)) { arguments[index] = cat.GetService(parameterType); } else if (parameter.HasDefaultValue) { arguments[index] = parameter.DefaultValue; } else { throw new InvalidOperationException($"Cannot create the instance of {type} whose constructor has non-registered parameter type(s)"); } } return(Activator.CreateInstance(type, arguments)); }
public static bool HasRegistry <T>(this Cat cat) => cat.HasRegistry(typeof(T));