配置AutoMapper以映射到具体类型,但允许在类定义中使用接口。

22

我有一些类似下面的代码。基本上它代表了从 Web 服务获取数据并将其转换为客户端对象。

void Main()
{
    Mapper.CreateMap<SomethingFromWebService, Something>();    
    Mapper.CreateMap<HasSomethingFromWebService, HasSomething>(); 
    // Service side
    var hasSomethingFromWeb = new HasSomethingFromWebService();
    hasSomethingFromWeb.Something = new SomethingFromWebService
            { Name = "Whilly B. Goode" };
    // Client Side                
    HasSomething hasSomething=Mapper.Map<HasSomething>(hasSomethingFromWeb);  
}    
// Client side objects
public interface ISomething
{
    string Name {get; set;}
}    
public class Something : ISomething
{
    public string Name {get; set;}
}    
public class HasSomething
{
    public ISomething Something {get; set;}
}    
// Server side objects
public class SomethingFromWebService
{
    public string Name {get; set;}
}    
public class HasSomethingFromWebService
{
    public SomethingFromWebService Something {get; set;}
}
我的问题是,我想在我的类中使用接口(在这种情况下为HasSomething.ISomething),但我需要让AutoMapper映射到具体类型。(如果我不映射到具体类型,则AutoMapper会为我创建代理,这会导致我的应用程序出现其他问题。)
上述代码给了我这个错误:
缺少类型映射配置或不支持的映射。
映射类型: SomethingFromWebService -> ISomething UserQuery+SomethingFromWebService -> UserQuery+ISomething
所以我的问题是,如何映射到具体类型并仍然在我的类中使用接口?
注意:我尝试添加此映射:
Mapper.CreateMap<SomethingFromWebService, ISomething>();

但是返回的对象不是类型为Something,它返回一个使用ISomething作为模板生成的代理。

1个回答

40

所以我想到了一些看起来有效的方法。

如果我添加这两个映射:

Mapper.CreateMap<SomethingFromWebService, Something>();
Mapper.CreateMap<SomethingFromWebService, ISomething>().As<Something>(); 

那么它按照我想要的方式工作。

我没有找到关于 "As" 方法的任何文档(尝试谷歌搜索一下吧!:),但它似乎是一种映射重定向。

例如:对于此映射(ISomething),将其解析为 Something


1
谢谢你,这对我帮助很大。除非我弄错了,你只需要第二个映射。我认为第二个映射必须使第一个映射变得多余了吧? - Ally Murray
2
不,你仍然需要第一个映射来针对具体类型进行映射,否则 AutoMapper 就不知道如何将 SomethingFromWebService 映射到 Something。 - TheWho
1
非常感谢!我已经苦苦挣扎了两个小时,这解决了我的问题! - Speuline

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接