Configure AutoMapper to map to concrete types but allow Interfaces in the definition of my class

别等时光非礼了梦想. 提交于 2019-12-03 06:56:05

问题


I have some code that is similar to what is below. Basically it represents getting data from a web service and converting it into client side objects.

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;}
}

The problem I have is that I want to use Interfaces in my classes (HasSomething.ISomething in this case), but I need to have AutoMapper map to concrete types. (If I don't map to concrete types then AutoMapper will create proxies for me. That causes other problems in my app.)

The above code gives me this error:

Missing type map configuration or unsupported mapping.

Mapping types: SomethingFromWebService -> ISomething
UserQuery+SomethingFromWebService -> UserQuery+ISomething

So my question is, how can I map to a concrete type and still use interfaces in my class?

NOTE: I tried adding this mapping:

Mapper.CreateMap<SomethingFromWebService, ISomething>();

But then the object returned is not of type Something it returns a generated Proxy using ISomething as the template.


回答1:


So I figured something that seems to work.

If I add these two mappings:

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

then it works as I want.

I have not been able to find any documentation on the 'As' method (try googling for that! :), but it seems to be a mapping redirection.

For example: For this Mapping (ISomething) resolve it As a Something.



来源:https://stackoverflow.com/questions/13075588/configure-automapper-to-map-to-concrete-types-but-allow-interfaces-in-the-defini

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!