AutoMapper of dependency Injection in. NET Core

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.