我有这种奇怪的AutoMapper行为。如果我有一个实现两个接口的类,它们都在class Dto {
public string StringValue {get;set;}
public int Value {get;set;}
}
中注册,只有其中一个被映射,我不明白为什么。看起来好像AutoMapper只映射了接口列表中第一个提到的接口。
有什么想法?请检查以下fiddler以查看问题所在。
来自fiddler的代码
我要映射的DTO:
interface ISourceA {
int Value {get;}
}
interface ISourceB {
string StringValue {get;}
}
接口 - 我想要映射的来源:
class MultiSource: ISourceA, ISourceB {
private readonly string _s;
private readonly int _v;
public MultiSource(int v, string s) {
_v = v;
_s = s;
}
int ISourceA.Value { get { return _v; }}
string ISourceB.StringValue { get { return _s; }}
}
class StringSource: ISourceB {
public StringSource(string value) {
StringValue = value;
}
public string StringValue {get; private set;}
}
......还有两个实现。一个有效,另一个不是真的:/
public class Program
{
public static void Main()
{
Mapper.CreateMap<ISourceA, Dto>();
Mapper.CreateMap<ISourceB, Dto>();
var ms = new MultiSource(234, "woefjweofij");
var ss = new StringSource("iuahergiuw");
// This one is fine
Console.WriteLine(JsonConvert.SerializeObject(Mapper.Map<Dto>((ISourceA)ms)));
// This one is the same as that above. This is not what I intended to have in return :/
Console.WriteLine(JsonConvert.SerializeObject(Mapper.Map<Dto>((ISourceB)ms)));
// This works as expected
Console.WriteLine(JsonConvert.SerializeObject(Mapper.Map<Dto>(ss)));
}
}
以下是我如何使用它:
{{1}}