简体   繁体   中英

Generic mapping in Automapper

Im trying to use automapper to convert Data Contracts to Client objects and vice versa.to reduce the lines of code and to make it simpler I want to create mapping dynamically. Lets say I'm calling 5 different services and each service will return same object like Employee but data will be different(If I need employee info from Microsoft I will call Microsoft service or if I want IBM employee details I will call IBM service so on).

My object is something like below..

Public class Employee
{
Public string Id{get;set;}
Public string Division{get;set;}
Public PersonDetails person{get;set;}
}
Public class PersonDetails
{
Public string Name{get;set;}
Public string Email{get;set;}
Public string contact{get;set;}
}

Using Automapper I can write something below..

 Mapper.CreateMap<Service1. PersonDetails, PersonDetails >();
   Mapper.CreateMap<Service1.Employee, Employee>()
        .ForMember(DEST=>DEST. PersonDetails,M=>M.MapFrom(Q=>Q. PersonDetails));
   Mapper.CreateMap<Service2. PersonDetails, PersonDetails >();
   Mapper.CreateMap<Service2.Employee, Employee>()
         .ForMember(DEST=>DEST.PersonDetails,M=>M.MapFrom(Q=>Q. PersonDetails));

ButI have to write same similar logic 5 times since i'm calling 5 different services.

Is there any way I can do this dynamically meaning i want to tell Automapper about source at runtime..

Please advise!!!

looks like you should be able to map from an interface instead of the service itself.

public interface IEmployeeServiceResponce
{
    Employee {get;}
    PersonDetails{get;}
}

then have each service implement that interface.

This articular may articulate my suggestion a little more

if the return is not identical to the interface then I would recommend implementing the Adapter Patter to uniform them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM