Example of the AutoMapper injection method in. NET Core, coreautomapper
This article mainly introduces the dependency injection of AutoMapper in. NET Core and shares the content for your reference. I will not talk about it much below. Let's take a look at the detailed introduction:
Recently, in the review code, I found that my colleagues did not use the Code as they did in other projects.AutoMapper.Mapper.Initialize()
The static method configures the ing, but uses the dependency injection IMapper interface.
services.AddSingleton<IMapper>(new Mapper(new MapperConfiguration(cfg =>{ cfg.CreateMap<User, MentionUserDto>();})));
So I took the opportunity to learn about it and found AutoMapper. Extensions. Microsoft. DependencyInjection on github.AutoMapper.Profile
Configure ing
public class MappingProfile : Profile{ public MappingProfile() { CreateMap<User, MentionUserDto>(); }}
ThenAddAutoMapper()
Dependency injection, which automatically finds all subclasses inherited from the Profile in the current Assembly and adds them to the configuration.
services.AddAutoMapper();
When projectid is used
.Take(10).ProjectTo<MentionUserDto>().ToListAsync();
If you useAddSingleton<IMapper>()
, The following error occurs (For details, refer to the FAQ ):
Mapper not initialized. Call Initialize with appropriate configuration.
UseAddAutoMapper()
The same problem occurs when UseStaticRegistration is set to false.
The solution is to pass parameters to projectid._mapper.ConfigurationProvider
(Note:The parameter _ mapper is invalid)
.ProjectTo<MentionUserDto>(_mapper.ConfigurationProvider)
For the method of self-dependent injection, referAutoMapper.Extensions.Microsoft.DependencyInjection
Implementation
services.AddSingleton(config);return services.AddScoped<IMapper>(sp => new Mapper(sp.GetRequiredService<IConfigurationProvider>(), sp.GetService));
The following method is used. If you do not want to useAddAutoMapper()
Profile is automatically located through reflection. This method is recommended.
AutoMapper.IConfigurationProvider config = new MapperConfiguration(cfg =>{ cfg.AddProfile<MappingProfile>();});services.AddSingleton(config);services.AddScoped<IMapper, Mapper>();
Summary
The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.