public static Instance Create(IReadOnlyContainer container, Type type, IReadOnlyDictionary <Type, object> unknownTypes) { Check.ArgumentIsNull(container, nameof(container)); Check.ArgumentIsNull(type, nameof(type)); Check.ArgumentIsNull(unknownTypes, nameof(unknownTypes)); var constructorsWithInjectAttr = InjectAttributeHelper.GetConstructors(type); if (constructorsWithInjectAttr.Count > 1) { throw new ContainerException($"Ambiguous usage of 'Inject' attribute on constructors of type '{type}'. Only one constructor can be marked with 'Inject' attribute."); } if (constructorsWithInjectAttr.Count == 0) { return(CreateInstanceUsingDefaultConstructor(type)); } Check.Assert(constructorsWithInjectAttr.Count == 1, "constructorsWithInjectAttr.Count == 1"); return(CreateInstanceUsingCustomConstructor(container, constructorsWithInjectAttr.Single(), unknownTypes)); }
public static void Inject(IReadOnlyContainer container, object instance, IReadOnlyDictionary <Type, object> unknownTypes) { Check.ArgumentIsNull(container, nameof(container)); Check.ArgumentIsNull(instance, nameof(instance)); Check.ArgumentIsNull(unknownTypes, nameof(unknownTypes)); var type = instance.GetType(); var propertiesWithInjectAttr = InjectAttributeHelper.GetProperties(type); CheckTypesOfPropertiesAreRegistered(container, type, propertiesWithInjectAttr, unknownTypes); foreach (var propertyInfo in propertiesWithInjectAttr) { var propertyType = propertyInfo.PropertyType; var instanceOfPropertyType = container.Contains(propertyType) ? container.Get(propertyType) : unknownTypes.First(kv => propertyType.IsAssignableFrom(kv.Key)).Value; propertyInfo.SetValue(instance, instanceOfPropertyType, null); } }