Dagrooms
Dagrooms

Reputation: 1564

AutoMapper generic conversion

I've been using AutoMapper and would like to take generic conversion one step further; instead of saying something like

cfg.CreateMap<Container<int>, int>()
    .ConvertUsing(new ContainerConverter<Container<int>, int>());

I would rather set the AutoMapper to know how to map any Container, such as:

cfg.CreateMap<Container<T>, T>()
    .ConvertUsing(new ContainerConverter<Container<T>, T>());

Since all conversions from Container to T are the same, it would be pointless to re-define this conversion for all of the classes I am converting.

Upvotes: 4

Views: 1679

Answers (1)

Kyle
Kyle

Reputation: 1043

Create your own map method as a generic, here is a basic example that you could modify as needed

/// <summary>
/// Maps one object into a new object of another type
/// </summary>
public static TResult Map<TSource, TResult>(this TSource source)
    where TSource : class
    where TResult : class, new()
{
    var ret = new TResult();
    source.Map(ret);
    return ret;
}

/// <summary>
/// Maps one object into an existing object of another type
/// </summary>
public static void Map<TSource, TResult>(this TSource source, TResult destination)
    where TSource : class
    where TResult : class
{
    if (Mapper.FindTypeMapFor<TSource, TResult>() == null)
        Mapper.CreateMap<TSource, TResult>();
    Mapper.Map(source, destination);
}

Upvotes: 2

Related Questions