I am using auto mapping first time.
I am working on c# application and I want to use auto mapper.
(I just want to know how to use it, so I don't have asp.net app neither MVC app.)
I have three class library projects.
I want to write transfer process in the service project.
So I want to know how and where should I configure the Auto Mapper ?
Where do I configure AutoMapper? ¶ Configuration should only happen once per AppDomain. That means the best place to put the configuration code is in application startup, such as the Global.
You can use AutoMapper to map any set of classes, but the properties of those classes have identical names. If the property names don't match, you should manually write the necessary code to let AutoMapper know which properties of the source object it should map to in the destination object.
First install the NuGet Package Manager in your Visual Studio IDE. Once done, go to "Tools" -> "Library Packet Manager" -> "Packet manager Console". Press Enter. This will install AutoMapper and the next time you open MVC application in Visual Studio, it will automatically add a DLL reference to the project.
So based on Bruno's answer here and John Skeet's post about singletons I came up with the following solution to have this run only once and be completely isolated in class library unlike the accepted answer which relies on the consumer of the library to configure the mappings in the parent project:
public static class Mapping { private static readonly Lazy<IMapper> Lazy = new Lazy<IMapper>(() => { var config = new MapperConfiguration(cfg => { // This line ensures that internal properties are also mapped over. cfg.ShouldMapProperty = p => p.GetMethod.IsPublic || p.GetMethod.IsAssembly; cfg.AddProfile<MappingProfile>(); }); var mapper = config.CreateMapper(); return mapper; }); public static IMapper Mapper => Lazy.Value; } public class MappingProfile : Profile { public MappingProfile() { CreateMap<Source, Destination>(); // Additional mappings here... } }
Then in your code where you need to map one object to another you can just do:
var destination = Mapping.Mapper.Map<Destination>(yourSourceInstance);
NOTE: This code is based on AutoMapper 6.2 and it might require some tweaking for older versions of AutoMapper.
You can place the configuration anywhere:
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() { ...... }
But it has to be called by the application using the libraries at some point:
void Application_Start() { AutoMapperConfiguration.Configure(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With