我正在尝试在 n 层应用程序上使用具有依赖注入(inject)配置的 Automapper。
public class ApplicationMapping : Profile
{
public ApplicationMapping()
{
RegisterMappings();
Mapper.AssertConfigurationIsValid();
}
private void RegisterMappings()
{
CreateMap<IEnumerable<App>, ListAppsDto>()
.ForMember(dest => dest.Apps,
opt => opt.MapFrom(src =>
Mapper.Map<IEnumerable<App>, List<App>>(src.ToList())
)
);
}
}
这个类在我的 Application
里面dll,我放置服务和 DTO 的地方。同样在这个 dll 中,我有一个扩展方法来注册映射:
public static class MappingServiceExtension
{
public static void AddApplicationMappings(this IServiceCollection services)
{
var mapperConfig = new MapperConfiguration(config =>
{
config.AddProfile<ApplicationMapping>();
});
IMapper mapper = mapperConfig.CreateMapper();
services.AddSingleton(mapper);
}
}
然后在我的 WebAPI 项目中,在 Startup.cs
上我放的课:
services.AddApplicationMappings();
我通常在我的服务中将它与 DI 一起使用:
public class AppService : IAppService
{
private readonly IAppRepository _appRepository;
private readonly IMapper _mapper;
public TruckService(IAppRepository appRepository, IMapper mapper)
{
_appRepository = appRepository;
_mapper = mapper;
}
}
我想这样使用。但当 Mapper.AssertConfigurationIsValid();
时我遇到异常行运行,说:
'Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance.'
我在这里缺少什么?问题似乎出在 Mapper.Map<IEnumerable<App>, List<App>>(src.ToList())
代码行。
但是我怎样才能获得 Mapper
的实例那里不使用静态 Mapper
?
最佳答案
Mapper.AssertConfigurationIsValid();
这会调用静态 IMapper
实例,该实例在不使用依赖注入(inject)的情况下使用。由于您从未设置静态映射器,因此使用它将会失败。
您想要做的是在实际映射器实例(您注册为单例的实例)上调用 AssertConfigurationIsValid
。因此,您应该从映射器配置文件中删除断言,然后在 AddApplicationMappings
方法中调用它:
IMapper mapper = mapperConfig.CreateMapper();
mapper.AssertConfigurationIsValid();
services.AddSingleton(mapper);
关于c# - 将 Automapper 与 ASP.NET Core 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56228059/