I have three projects in my solution, with the .net core 5:
- Demo.DAL (Library)
- Demo.BLL (Library)
- Demo.PL (MVC)
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.