Skip to content

Instantly share code, notes, and snippets.

@amoerie
Created December 22, 2012 17:22
Show Gist options
  • Save amoerie/4360044 to your computer and use it in GitHub Desktop.
Save amoerie/4360044 to your computer and use it in GitHub Desktop.
/// <summary>
/// Custom injection to support nested DTO properties
/// </summary>
public class DtoInjection: LoopValueInjection
{
/// <summary>
/// If one of the types implements IDto, check if its generic type parameter
/// matches the other type
/// Otherwise, just use the default typematcher.
/// </summary>
/// <param name="sourceType"></param>
/// <param name="targetType"></param>
/// <returns></returns>
protected override bool TypesMatch(Type sourceType, Type targetType)
{
if (IsDtoAndModelType(sourceType, targetType) || IsDtoAndModelType(targetType, sourceType))
return true;
return base.TypesMatch(sourceType, targetType);
}
/// <summary>
/// If the target property or source property is a DTO, we'll need to recursively use
/// this class to set the value
/// </summary>
/// <param name="v"></param>
/// <returns></returns>
protected override object SetValue(object v)
{
if (IsDtoAndModelType(SourcePropType, TargetPropType) || IsDtoAndModelType(TargetPropType, SourcePropType))
{
var target = Activator.CreateInstance(TargetPropType);
if(v != null)
target.InjectFrom<DtoInjection>(v);
return target;
}
return base.SetValue(v);
}
/// <summary>
/// Returns true if the dtoType implements IDto with generic type modelType
/// </summary>
/// <param name="dtoType"></param>
/// <param name="modelType"></param>
/// <returns></returns>
private bool IsDtoAndModelType(Type dtoType, Type modelType)
{
// get DTO interface from dtoType
var dtoInterface = dtoType.GetInterfaces()
.FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDto<>));
// if dtoType doesn't implement IDto, return false
if (dtoInterface == null)
return false;
// Get the generic type argument and check if it matches the modeltype
var dtoModelType = dtoInterface.GetGenericArguments().First();
return dtoModelType == modelType;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment