gpt4 book ai didi

c# - Automapper 在 Profile 类中注入(inject) DbContext

转载 作者:行者123 更新时间:2023-11-30 21:35:28 29 4
gpt4 key购买 nike

我有以下映射配置文件

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,因此我必须以某种方式将其注入(inject) 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解决方案,但我收到了 “无法解析来自根提供商的作用域服务‘FootballPredictions.DAL.FootballPredictionsContext’。”

最佳答案

我最近遇到了一个类似的问题,这是因为我试图将一个服务注入(inject)到一个生命周期更长的服务中(例如 transient 和作用域)。与 DomainProfile 类关联的生命周期是多少?您是否尝试过将其更改为 Scoped 或 Transient 以查看是否有帮助?

由@DimitarTsonev 实现:因此,将映射器范围更改为

services.AddScoped(provider => new MapperConfiguration(cfg =>
{
cfg.AddProfile(new DomainProfile(provider.GetService<FootballPredictionsContext>()));
}).CreateMapper());

解决了问题

关于c# - Automapper 在 Profile 类中注入(inject) DbContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49197656/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com