Skip to main content

Consume AutoMapper in a Singleton instance during impliment an IHostedService

· One min read

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

What is the difference between services.AddTransient, service.AddScoped and service.AddSingleton methods in ASP.NET Core?

· One min read

1. Transient objects are always different; a new instance is provided to every controller and every service. 2. Scoped objects are the same within a request, but different across different requests. 3. Singleton objects are the same for every object and every request.

Refs: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.2#service-lifetimes-and-registration-options https://stackoverflow.com/questions/38138100/what-is-the-difference-between-services-addtransient-service-addscoped-and-serv

ClustrMaps