Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper inject DbContext in the Profile class

I have the following mapping profile

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)));
    }
}

As you can see, some of the mappings are using the DbContext, so I have to somehow inject it in the DomainProfile

In the Startup class I am initializing the Automapper normally

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();
        }

I tried this solution, but I am receiving 'Cannot resolve scoped service 'FootballPredictions.DAL.FootballPredictionsContext' from root provider.'

like image 788
Dimitar Tsonev Avatar asked Mar 06 '23 17:03

Dimitar Tsonev


1 Answers

I've come across a similar problem recently and it was down to the fact that I was trying to inject a service into a service with a longer lifetime (e.g. transient and scoped). What lifetime is associated with the DomainProfile class? Have you tried changing that to Scoped or Transient to see if that helps?

As implemented by @DimitarTsonev: So, changing the mapper scope to

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

fixed the issue

like image 177
Simply Ged Avatar answered Mar 09 '23 05:03

Simply Ged