AggregateException: Some services are not able to be constructed

1

I have a project in .NET 5.0, everything worked fine - build, execute, just work - until 10th April.

Now I have a lot of error with registering services.

Unhandled exception. System.AggregateException: Some services are not able to be constructed 
(Error while validating the service descriptor 'ServiceType: AService.DataAccess.MyDbContext 
Lifetime: Scoped ImplementationType: AService.DataAccess.MyDbContext': Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbSet`1[AService.Domain.Entities.B.B]' while 
attempting to activate 'AService.DataAccess.MyDbContext'.) (Error while validating the 
service descriptor 'ServiceType: 
MediatR.IRequestHandler`2[AService.Api.Queries.B.GetAllQuery, 
System.Collections.Generic.IEnumerable`1[AService.Api.Queries.B.Dtos.BDto]] 
Lifetime: Transient ImplementationType: 
AService.Queries.B.GetAllQueryHandler': Unable to resolve service for type 
'Microsoft.EntityFrameworkCore.DbSet`1[AService.Domain.Entities.B.B]' while 
attempting to activate 'AService.DataAccess.MyDbContext'.)

I short - every repository, every service, everything that needs to be registered and IS registered in Startup.cs as below:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers().AddNewtonsoftJson(options => 
        options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);

    services.AddDbContext<MyDbContext>();
    
    services.AddStackExchangeRedisExtensions<NewtonsoftSerializer>((options) => 
        Configuration.GetSection("Redis").Get<RedisConfiguration>());
    
    services.AddMediatR(Assembly.GetExecutingAssembly());

    services.AddTransient<IARepository, ARepository>();
    services.AddTransient<IBRepository, BRepository>();
    services.AddTransient<ICRepository, CRepository>();

    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo {Title = "Service API", Version = "v1.0"});
    });

}


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseStaticFiles();
    app.UseRouting();
    app.UseCors();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });

    app.UseSwagger();

    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "Menu Service API v1.0");
    });
}

Program.cs

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
}

I don't know is it a problem with Rider version (I program on macos). When I debug I have the following error message:

An IL variable is not available at the current native IP. (0x80131304). The error code is CORDBG_E_IL_VAR_NOT_AVAILABLE, or 0x80131304.

Have anybody an idea what can cause that error? As I said at the beginning, everything worked fine few days before.

EDIT - added MyDbContext:

public class MyDbContext : DbContext
{
    public MyDbContext(DbSet<A> a, DbSet<B> b, DbSet<C> c)
    {
        As = a;
        Bs = b;
        Cs = c;
    }

    public DbSet<A> As { get; }
    public DbSet<B> Bs { get; }
    public DbSet<C> Cs { get; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"Server=localhost;Database=my-db;User=user;Password=password");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<B>()
            .HasOne(mi => mi.A)
            .WithMany(m => m.Bs)
            .HasForeignKey(mi => mi.AId);

        modelBuilder.Entity<B>()
            .Property(mi => mi.Xs)
            .HasConversion(
                a => string.Join(',', a),
                a => a.Split(',', StringSplitOptions.RemoveEmptyEntries));
    }
}
c#
.net
asp.net-core
dependency-injection
.net-5
asked on Stack Overflow Apr 12, 2021 by paweto • edited Apr 12, 2021 by WΩLLE - ˈvɔlə

1 Answer

3

Remove the constructor and add setters to DbSet properties:

public class MyDbContext : DbContext
{
    public DbSet<A> As { get; private set; } // or public setters
    public DbSet<B> Bs { get; private set; }
    public DbSet<C> Cs { get; private set; }
    .....
}

DI container uses constructors to do it's magic and tries to resolve and inject all constructor parameters. Since you haven't (and you should not) registered DbSet's - they can not be resolved.

answered on Stack Overflow Apr 12, 2021 by Guru Stron • edited Apr 12, 2021 by Guru Stron

User contributions licensed under CC BY-SA 3.0