How to set up Automapper in ASP.NET Core
I want to extend @theutz's answers - namely this line :
// services.AddAutoMapper(typeof(Startup)); // <-- newer automapper version uses this signature.
There is a bug (probably) in AutoMapper.Extensions.Microsoft.DependencyInjection version 3.2.0. (I'm using .NET Core 2.0)
This is tackled in this GitHub issue. If your classes inheriting AutoMapper's Profile class exist outside of assembly where you Startup class is they will probably not be registered if your AutoMapper injection looks like this:
services.AddAutoMapper();
unless you explicitly specify which assemblies to search AutoMapper profiles for.
It can be done like this in your Startup.ConfigureServices:
services.AddAutoMapper(<assembies> or <type_in_assemblies>);
where "assemblies" and "type_in_assemblies" point to the assembly where Profile classes in your application are specified. E.g:
services.AddAutoMapper(typeof(ProfileInOtherAssembly), typeof(ProfileInYetAnotherAssembly));
I suppose (and I put emphasis on this word) that due to following implementation of parameterless overload (source code from GitHub) :
public static IServiceCollection AddAutoMapper(this IServiceCollection services)
{
return services.AddAutoMapper(null, AppDomain.CurrentDomain.GetAssemblies());
}
we rely on CLR having already JITed assembly containing AutoMapper profiles which might be or might not be true as they are only jitted when needed (more details in this StackOverflow question).
Step To Use AutoMapper with ASP.NET Core.
Step 1. Installing AutoMapper.Extensions.Microsoft.DependencyInjection from NuGet Package.
Step 2. Create a Folder in Solution to keep Mappings with Name "Mappings".
Step 3. After adding Mapping folder we have added a class with Name "MappingProfile" this name can anything unique and good to understand.
In this class, we are going to Maintain all Mappings.
Step 4. Initializing Mapper in Startup "ConfigureServices"
In Startup Class, we Need to Initialize Profile which we have created and also Register AutoMapper Service.
Mapper.Initialize(cfg => cfg.AddProfile<MappingProfile>());
services.AddAutoMapper();
Code Snippet to show ConfigureServices Method where we need to Initialize and Register AutoMapper.
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
// Start Registering and Initializing AutoMapper
Mapper.Initialize(cfg => cfg.AddProfile<MappingProfile>());
services.AddAutoMapper();
// End Registering and Initializing AutoMapper
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}}
Step 5. Get Output.
To Get Mapped result we need to call AutoMapper.Mapper.Map and pass Proper Destination and Source.
AutoMapper.Mapper.Map<Destination>(source);
CodeSnippet
[HttpPost]
public void Post([FromBody] SchemeMasterViewModel schemeMaster)
{
if (ModelState.IsValid)
{
var mappedresult = AutoMapper.Mapper.Map<SchemeMaster>(schemeMaster);
}
}
I figured it out! Here's the details:
Add the main AutoMapper Package to your solution via NuGet.
Add the AutoMapper Dependency Injection Package to your solution via NuGet.
Create a new class for a mapping profile. (I made a class in the main solution directory called
MappingProfile.cs
and add the following code.) I'll use aUser
andUserDto
object as an example.public class MappingProfile : Profile { public MappingProfile() { // Add as many of these lines as you need to map your objects CreateMap<User, UserDto>(); CreateMap<UserDto, User>(); } }
Then add the AutoMapperConfiguration in the
Startup.cs
as shown below:public void ConfigureServices(IServiceCollection services) { // .... Ignore code before this // Auto Mapper Configurations var mapperConfig = new MapperConfiguration(mc => { mc.AddProfile(new MappingProfile()); }); IMapper mapper = mapperConfig.CreateMapper(); services.AddSingleton(mapper); services.AddMvc(); }
To invoke the mapped object in code, do something like the following:
public class UserController : Controller { // Create a field to store the mapper object private readonly IMapper _mapper; // Assign the object in the constructor for dependency injection public UserController(IMapper mapper) { _mapper = mapper; } public async Task<IActionResult> Edit(string id) { // Instantiate source object // (Get it from the database or whatever your code calls for) var user = await _context.Users .SingleOrDefaultAsync(u => u.Id == id); // Instantiate the mapped data transfer object // using the mapper you stored in the private field. // The type of the source object is the first type argument // and the type of the destination is the second. // Pass the source object you just instantiated above // as the argument to the _mapper.Map<>() method. var model = _mapper.Map<UserDto>(user); // .... Do whatever you want after that! } }