我有以下映射配置文件
public class DomainProfile : Profile
{
private FootballPredictionsContext m_Context;
public DomainProfile(FootballPredictionsContext context)
{
m_Context = context;
}
public DomainProfile()
{
CreateMap<TipModel, Tip>()
.ForMember(tip => tip.BetType, m => m.MapFrom(x => m_Context.BetTypes.First(y => y.Name == x.BetType)))
.ForMember(tip => tip.BetCategory, m => m.MapFrom(x => m_Context.BetCategories.First(y => y.Name == x.BetCategory)))
.ForMember(tip => tip.Sport, m => m.MapFrom(x => m_Context.Sports.First(y => y.Name == x.Sport)))
.ForMember(tip => tip.Tipster, m => m.MapFrom(model => m_Context.Tipsters.First(y => y.Username == model.Tipster)));
}
}
正如您所看到的,某些映射正在使用DbContext
,因此我必须以某种方式将其注入DomainProfile
在Startup类中,我正在初始化Automapper
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped(typeof(IUnificator), typeof(Unificator));
services.AddDbContext<FootballPredictionsContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Database")));
services.AddDbContext<UnificationContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Database")));
services.AddSingleton(provider => new MapperConfiguration(cfg =>
{
cfg.AddProfile(new UserProfile(provider.GetService<IUserManager>()));
}).CreateMapper());
services.AddMvc();
}
我尝试了this解决方案,但我收到了'Cannot resolve scoped service 'FootballPredictions.DAL.FootballPredictionsContext' from root provider.'
答案 0 :(得分:1)
我最近遇到过类似的问题,这是因为我试图将服务注入到具有更长生命周期的服务(例如,瞬态和范围)。与DomainProfile类相关的生命周期是什么?您是否尝试将其更改为Scoped或Transient以查看是否有帮助?
由@DimitarTsonev实施: 因此,将映射器范围更改为
services.AddScoped(provider => new MapperConfiguration(cfg =>
{
cfg.AddProfile(new DomainProfile(provider.GetService<FootballPredictionsContext>()));
}).CreateMapper());
解决了问题
答案 1 :(得分:0)
假设您实际上已经注册了上下文(例如services.AddDbContext
),则该异常的最可能原因是您在之前注册了AutoMapper &# 39;重新注册上下文。在执行services.AddAutoMapper
之前,请确保首先注册您的上下文。