Consume AutoMapper in a Singleton instance during impliment an IHostedService

AutoMapper中的AddAutoMapper默认使用AddScoped方式把AutoMapper实例注册到.NET Core DI中的:

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddAutoMapper();
    ...
}

 

如果你在一个IHostedService注册了一个Singleton实例, 该Singleton实例的构造函数中通过DI注入的方式引用了IMapper, 将会发生如下错误:

'Cannot consume scoped service 'AutoMapper.IMapper' from singleton 'XXX'.'

 

解决方法是把IMapper也以Singleton模式注册:

public class AutoMapperProfile : Profile
{
    public AutoMapperProfile()
    {
        CreateMap<SourceClass, DestinationClass>();
    }
}
public void ConfigureServices(IServiceCollection services)
{
    ...
    var mappingConfig = new MapperConfiguration(mc =>
    {
        mc.AddProfile(new AutoMapperProfile());
    });

    IMapper mapper = mappingConfig.CreateMapper();
    services.AddSingleton(mapper);
    ...
}

 

Refs:

https://stackoverflow.com/questions/40275195/how-to-setup-automapper-in-asp-net-core

Leave a Comment