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

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

void Main() { Mapper.CreateMap(); Mapper.CreateMap(); // Service side var hasSomethingFromWeb = new HasSomethingFromWebService(); hasSomethingFromWeb.Something = new SomethingFromWebService { Name = "Whilly B. Goode" }; // Client Side HasSomething hasSomething=Mapper.Map(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(); 

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

所以我认为似乎有用的东西。

如果我添加这两个映射:

 Mapper.CreateMap(); Mapper.CreateMap().As(); 

然后它按我的意愿工作。

我无法找到关于’As’方法的任何文档(尝试使用google搜索!:),但它似乎是一个映射重定向。

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