Recently found in the review code that colleagues did not use AutoMapper.Mapper.Initialize () static methods to configure the mappings like other projects, but instead used the method of dependency injection Imapper interfaces
Services. Addsingleton<imapper> ( new Mapper (new mapperconfiguration (cfg ={ cfg). Createmap<user, mentionuserdto>();} ));
So take the opportunity to learn about it, discover AutoMapper.Extensions.Microsoft.DependencyInjection on GitHub, and use it just to configure the mapping via Automapper.profile
Public class mappingprofile:profile{ public mappingprofile () { Createmap<user, Mentionuserdto>(); }}
The dependency injection is then done through Addautomapper (), which automatically finds all the subclasses of the inherited profile from the current assembly to be added to the configuration
Services. Addautomapper ();
Later found in the use of Projectto
. Take (ten). Projectto<MentionUserDto>
If you find yourself using addsingleton<imapper> (), you will see the following error (see BO):
Mapper not initialized. Call Initialize with appropriate configuration.
The same problem occurs when you use Addautomapper () and the usestaticregistration is false.
The solution is to projectto the _mapper. Configurationprovider (Note: Pass _mapper not)
. Projectto<mentionuserdto> (_mapper. Configurationprovider)
For their own dependency injection operation, later refer to the implementation of AutoMapper.Extensions.Microsoft.DependencyInjection
Services. Addsingleton (config); return New Mapper (sp. Getrequiredservice<iconfigurationprovider> (), Sp. GetService));
This approach is recommended if you do not want to use Addautomapper () to automatically find the profile using reflection.
New Mapperconfiguration (cfg ={ cfg). Addprofile<MappingProfile>();}); Services. Addsingleton (config); services. addscoped<imapper, mapper> ();
AutoMapper of dependency Injection in. NET Core