[英]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. 在Automapper中可以映射开放的泛型 ,但是尝试将其与自定义类型转换器结合使用时出现了一些问题。
The following 下列
cfg.CreateMap(typeof(IEnumerable<>), typeof(MyCustomCollectionType<>))
.ConvertUsing(typeof(MyConverter));
with MyConverter looking like this: MyConverter看起来像这样:
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
mscorlib.dll中的'System.InvalidOperationException'
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.