public static class AutoMapperConfiguration
{
public static IMapper CreateMapper()
{
var mapperConfig = new MapperConfiguration(cfg =>
{
cfg.AddProfile<ModelProfile>();
cfg.AddProfile<DtoProfile>();
cfg.AddProfile<ItmProfile>();
});
return mapperConfig.CreateMapper();
}
}
//Registering my service:
builder.Services.AddSingleton<IMapper>(AutoMapperConfiguration.CreateMapper());
我也尝试在 Autofac 的帮助下注册。我在注册时没有遇到问题,但在解析 IMapper 时,我收到异常“调用目标已抛出异常”。
container.Register(cfc => new MapperConfiguration(cfg =>
{
cfg.AddProfile<ModelProfile>();
cfg.AddProfile<DtoProfile>();
cfg.AddProfile<ItmProfile>();
}));
container.Register(ctx => ctx.Resolve<MapperConfiguration>().CreateMapper()).As<IMapper>()
.SingleInstance();
正如 @LucianBargaoanu 分享的帖子中提到的,通过从 Nuget 添加“AutoMapper”13.0,我可以访问“AddAutoMapper”方法。我将我的个人资料添加到其中。这对我有用。
builder.Services.AddAutoMapper(typeof(ModelProfile), typeof(DtoProfile), typeof(ItmProfile));