【发布时间】:2019-10-07 05:51:49
【问题描述】:
我正在尝试在 n 层应用程序上使用 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.Map 方法的任何调用,并且如果您使用 ProjectTo 或 UseAsDataSource 扩展方法,请确保传入适当的 IConfigurationProvider实例。'
我在这里缺少什么?问题似乎出在Mapper.Map<IEnumerable<App>, List<App>>(src.ToList()) 代码行。
但是如何在不使用静态 Mapper 的情况下获得 Mapper 的实例?
【问题讨论】:
-
你需要 Custom type converter 来代替
IEnumerable<App>, List<App>并从ResolutionContext获取mapper。 -
它没有解决问题,因为我仍然需要在 CustomTypeConverter 类上使用
context.Mapper.Map<...>。仍然出现同样的错误。
标签: c# asp.net-core automapper