public override void Activate() { IDictionary <string, Lazy <object> > valuesLazy = ImportValues.ToDictionary( x => x.Key.MemberName, v => v.Value); if (CachedInstance == null && this.Definition.ParameterlessConstructor) { _cachedInstance = CustomActivator.CreateInstance(Definition.GetPartType()); var unpackValues = valuesLazy.ToDictionary(k => k.Key, v => v.Value.Value); CustomActivator.PopulateObjectProperties(_cachedInstance, unpackValues); } else if (this.Definition.ParameterlessConstructor) { var unpackValues = valuesLazy.ToDictionary(k => k.Key, v => v.Value.Value); CustomActivator.PopulateObjectProperties(_cachedInstance, unpackValues); } else { var constructor = Definition.GetConstructor(); var requiredParameters = constructor.GetParameters(); //Sorting imports to match constructor order object[] unpackValues = new SortedDictionary <string, Lazy <object> >(valuesLazy) .Zip(requiredParameters, (lazyValues, required) => new { lazyValues, required }) .OrderBy(x => x.required.Name) .Select(x => x.lazyValues.Value.Value) .ToArray <object>(); _cachedInstance = Definition.GetConstructor().Invoke(unpackValues); } }
public void ReflectionHelperDeveSobrescreverPropriedadesDoObjetoJaInstanciado() { var myObject = new InstantiableObject(); myObject.Integer = 1; myObject.Boolean = false; myObject.AnotherInteger = 2; myObject.AnotherBoolean = false; myObject.IntegerNullable = 3; var properties = new Dictionary <string, object>(); properties.Add("Integer", "10"); properties.Add("Boolean", "true"); properties.Add("AnotherInteger", "20"); properties.Add("AnotherBoolean", "true"); properties.Add("IntegerNullable", null); CustomActivator.PopulateObjectProperties(myObject, properties); myObject.Integer.Should().Be(10); myObject.Boolean.Should().Be(true); myObject.AnotherInteger.Should().Be(20); myObject.AnotherBoolean.Should().Be(true); myObject.IntegerNullable.Should().Be(null); }