Example method of dependency injection AutoMapper in NET Core

  • 2021-10-24 19:20:40
  • OfStack

This article mainly introduces the related contents of dependency injection AutoMapper in. NET Core, and shares them for your reference and study. The following words are not much to say, let's take a look at the detailed introduction:

I recently found that colleagues didn't use it like other projects when I was in review code AutoMapper.Mapper.Initialize() The static method configures the mapping, but uses the way of dependency injection IMapper interface


services.AddSingleton<IMapper>(new Mapper(new MapperConfiguration(cfg =>
{
 cfg.CreateMap<User, MentionUserDto>();
})));

So I took the opportunity to learn about 1 and found AutoMapper. Extensions. Microsoft. DependencyInjection on github. To use it, I only need to pass AutoMapper.Profile Configuration mapping


public class MappingProfile : Profile
{
 public MappingProfile()
 {
  CreateMap<User, MentionUserDto>();
 }
}

And then through AddAutoMapper() Dependency injection, which automatically finds all subclasses inherited from Profile in the current assembly and adds them to the configuration


services.AddAutoMapper();

It was later discovered that when using ProjectTo,


.Take(10)
.ProjectTo<MentionUserDto>()
.ToListAsync(); 

Find that if you use it yourself AddSingleton<IMapper>() The following error will occur (see Bo Wen for details):


Mapper not initialized. Call Initialize with appropriate configuration.

Use AddAutoMapper() And the same problem will occur when UseStaticRegistration is false.

The solution is to pass parameters to ProjectTo _mapper.ConfigurationProvider (Note: I can't pass _ mapper)


.ProjectTo<MentionUserDto>(_mapper.ConfigurationProvider)

For the operation mode of your own dependency injection, refer to it later AutoMapper.Extensions.Microsoft.DependencyInjection Implementation of


services.AddSingleton(config);
return services.AddScoped<IMapper>(sp => new Mapper(sp.GetRequiredService<IConfigurationProvider>(), sp.GetService));

In the following way, if you don't want to use AddAutoMapper()  Automatically find out Profile by reflection, which is recommended


AutoMapper.IConfigurationProvider config = new MapperConfiguration(cfg =>
{
 cfg.AddProfile<MappingProfile>();
});
services.AddSingleton(config);
services.AddScoped<IMapper, Mapper>();

Summarize


Related articles: