简体   繁体   中英

Automapper custom converter for open generic

Mapping open generics is possible in Automapper, however I have come accros some issue trying to combine it with custom type converters.

The following

cfg.CreateMap(typeof(IEnumerable<>), typeof(MyCustomCollectionType<>))
.ConvertUsing(typeof(MyConverter));

with MyConverter looking like this:

class MyConverter : ITypeConverter<object, object>
{
    public object Convert(object source, object destination, ResolutionContext context)
    {
        //... do conversion
    }
}

does just throw an exception when the mapping is created:

'System.InvalidOperationException' in mscorlib.dll

Additional information: This operation is only valid on generic types.

How can I define a custom type converter for open generic types? What interface do I need to implement?

Converters for open generics need to be generic types. It would look something like:

public class MyConverter<TSource, TDest> 
    : ITypeConverter<IEnumerable<TSource>, MyCustomCollectionType<TDest>> {
    public MyCustomCollectionType<TDest> Convert(
        IEnumerable<TSource> source, 
        MyCustomCollectionType<TDest> dest, 
        ResolutionContext context) {
        // you now have the known types of TSource and TDest
        // you're probably creating the dest collection
        dest = dest ?? new MyCustomCollectionType<TDest>();
        // You're probably mapping the contents
        foreach (var sourceItem in source) {
            dest.Add(context.Mapper.Map<TSource, TDest>(sourceItem));
        }
        //then returning that collection
        return dest;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM