asp.net-mvcasp.net-core

When I run the project or try to apply an initial migration I get an AggregateException and an InvalidOperationException


I have three projects in my solution, with the .net core 5:

Demo.DAL: Contains the DbContext class in the Data folder.

namespace Demo.DAL.Data
{
    public class App_DbContext : DbContext
    {
        public App_DbContext(DbContextOptions<DbContext> options): base(options)
        {

        }
        public DbSet<Department> Departments { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
        }
    }
}

Demo.PL: This is the ConfigureServices method in the Startup class.

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();

    services.AddDbContext<App_DbContext>(optionsBuilder =>
    {
        optionsBuilder.UseSqlServer(Configuration.GetConnectionString("myConnection"));
    }
    );

}

I was trying to apply the dependency injection with the App_DbContext class.

When I remove this part from the ConfigureServices method

services.AddDbContext<App_DbContext>(optionsBuilder =>
    {
        optionsBuilder.UseSqlServer(Configuration.GetConnectionString("myConnection"));
    }
    );

the program runs with no exceptions and when I return it back the following exceptions appear.

AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Demo.DAL.Data.App_DbContext Lifetime: Scoped ImplementationType: Demo.DAL.Data.App_DbContext': Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[Microsoft.EntityFrameworkCore.DbContext]' while attempting to activate 'Demo.DAL.Data.App_DbContext'.) Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(IEnumerable serviceDescriptors, IServiceProviderEngine engine, ServiceProviderOptions options)

InvalidOperationException: Error while validating the service descriptor 'ServiceType: Demo.DAL.Data.App_DbContext Lifetime: Scoped ImplementationType: Demo.DAL.Data.App_DbContext': Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[Microsoft.EntityFrameworkCore.DbContext]' while attempting to activate 'Demo.DAL.Data.App_DbContext'. Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.ValidateService(ServiceDescriptor descriptor)

I found relevant questions about similar issues, I tried most of the mentioned solutions in their answers but none of them worked with me.


Solution

  • When I run the project or try to apply an initial migration I get an AggregateException and an InvalidOperationException

    Based on your shared code snippet and description along with the error message which indicates that, the issue you're encountering is due to a mismatch between the DbContextOptions type specified in your App_DbContext constructor and the type expected by Entity Framework Core's dependency injection system. I have successfully reproduce your issue, as you can see below:

    enter image description here

    Specifically, your App_DbContext constructor should expect DbContextOptions<App_DbContext> rather than DbContextOptions<DbContext>.

    If you have gone through the DbContext in dependency injection details, you would have seen that DbContextOptionsrequires your DbContext name, which is App_DbContext in your scenario.

    However, you are passing DbContextOptions<DbContext> as constructor which is incorrect.

    enter image description here

    In order to fix that, you should modify your dbContext as following:

    namespace Demo.DAL.Data
    {
        public class App_DbContext : DbContext
        {
            public App_DbContext(DbContextOptions<App_DbContext> options) : base(options)
            {
            }
    
            public DbSet<Department> Departments { get; set; }
    
            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
            }
        }
    }
    

    Note: After having above modification, double check your connection string and program.cs file. Then try executing migration command. If you need, you could take a look at this official document as a reference.