Configure AutoMapper to map to concrete types but

2019-03-14 15:17发布

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条回答
三岁会撩人
2楼-- · 2019-03-14 16:09

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.

查看更多
登录 后发表回答