I have created a custom injection class for ValueInjecter that does recursive injection for generic child collections, but that works with the existing target objects rather than cloning like the "CloneInjection" sample on the VI site. However, currently I am casting to a known type (ICollection<MyTargetType>), so the injection class is only good for the one hard coded type. I can't seem to figure a way to cast a generic dynamically, any suggestions? Here's the SetValue code for my "RecursiveInjection" class.
//for value types and string just return the value as is
if (c.SourceProp.Type.IsValueType || c.SourceProp.Type == typeof(string))
return c.SourceProp.Value;
if (c.SourceProp.Type.IsGenericType)
{
//handle IEnumerable<> also ICollection<> IList<> List<>
if (c.SourceProp.Type.GetGenericTypeDefinition().GetInterfaces().Contains(typeof(IEnumerable)))
{
var t = c.TargetProp.Type.GetGenericArguments()[0];
if (t.IsValueType || t == typeof(string)) return c.SourceProp.Value;
//get enumerable object in target
var targetCollection = c.TargetProp.Value as ICollection<MyTargetType>;
//possible to cast dynamically?
foreach (var o in c.SourceProp.Value as IEnumerable)
{
//get ID of source object
var sourceID = (int)o.GetProps().GetByName("ID").GetValue(o);
//find matching target object if there is one
var target = targetCollection.SingleOrDefault(x => x.ID == sourceID);
if (target != null)
{
target.InjectFrom<RecursiveInjection>(o);
}
}
return targetCollection;
}
}
Thanks, DanO