2014-10-20 8 views
18

Ich verwende Auto-Mapping zum ersten Mal.Wie Auto Mapper in Klassenbibliothek Projekt konfigurieren?

Ich arbeite an C# -Anwendung und ich möchte Auto Mapper verwenden.

(Ich will nur wissen, wie es zu benutzen, so dass ich nicht asp.net app weder MVC app.)

Ich habe drei Klassenbibliothek Projekte.

enter image description here

Ich möchte Transferprozess im Service-Projekt schreiben.

Also ich möchte wissen, wie und wo soll ich den Auto Mapper konfigurieren?

Antwort

20

Sie die Konfiguration überall platzieren können:

public class AutoMapperConfiguration 
{ 
    public static void Configure() 
    { 
     Mapper.Initialize(x => 
      { 
       x.AddProfile<MyMappings>();    
      }); 
    } 
} 

public class MyMappings : Profile 
{ 
    public override string ProfileName 
    { 
     get { return "MyMappings"; } 
    } 

    protected override void Configure() 
    { 
    ...... 
    } 

Aber es hat von der Anwendung aufgerufen werden, um die Bibliotheken an einem gewissen Punkt mit:

void Application_Start() 
    {    
     AutoMapperConfiguration.Configure(); 
    } 
0

Ich empfehle, dass Sie die instance based approach using an IMapper verwenden:

var config = new MapperConfiguration(cfg => { 
    cfg.AddProfile<AppProfile>(); 
    cfg.CreateMap<Source, Dest>(); 
}); 

IMapper mapper = config.CreateMapper(); 
// or 
IMapper mapper = new Mapper(config); 
var dest = mapper.Map<Source, Dest>(new Source()); 

So muss niemand außerhalb Ihrer Bibliothek eine Konfiguration aufrufen Rationsmethode. Sie können eine MapperConfiguration definieren und den Mapper von dort innerhalb der Klassenbibliothek erstellen.

Verwandte Themen