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.
So I figured something that seems to work.
If I add these two mappings:
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 itAs
aSomething
.