I'm getting this error :
Unable to create a 'DbContext' of type 'AppDbContext'. The exception 'Object reference not set to an instance of an object.' was thrown while attempting to create an instance. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
in my ASP.NET Core Web API project. I've been trying to fix this error for the past week, but I haven't been able to solve it.
I think all the code I wrote is correct, but I'm still getting this error. Every AI I've used has suggested that I create a design-time factory, but the result is still the same, I'm getting this error.
Here's my code - AppDBContext:
using Domain.Entites;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System.Reflection;
namespace Persistence.Context;
public class AppDbContext : IdentityDbContext<User, Role, string>
{
public AppDbContext(DbContextOptions options) : base(options)
{
}
public DbSet<Hotel> Hotels { get; set; }
public DbSet<Room> Rooms { get; set; }
public DbSet<RoomType> RoomTypes { get; set; }
public DbSet<Reservation> Reservations { get; set; }
public DbSet<Payment> Payments { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
}
}
Program.cs:
using Application;
using Domain.Entites;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Persistence;
using Persistence.Context;
var builder = WebApplication.CreateBuilder(args);
var connString = builder.Configuration.GetConnectionString("DBConn");
Console.WriteLine($"🔗 Program.cs - Connection String: {connString}");
// Add services to the container.
builder.Services.AddPersistenceServices(builder.Configuration);
builder.Services.AddAppServices();
builder.Services.AddControllers();
builder.Services.AddIdentity<User, Role>(opt =>
{
opt.Password.RequiredUniqueChars = 1;
opt.Password.RequireDigit = true;
opt.Password.RequiredLength = 16;
opt.Password.RequireLowercase = true;
opt.Password.RequireUppercase = true;
opt.Password.RequireNonAlphanumeric = true;
opt.User.RequireUniqueEmail = true;
opt.SignIn.RequireConfirmedEmail = true;
})
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();
//builder.Services.AddDataProtection();
builder.Services.AddOpenApi();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
//using(var servicescope = app.Services.CreateScope())
//{
// var services = servicescope.ServiceProvider;
// var dbcontext = services.GetRequiredService<AppDbContext>();
// dbcontext.Database.EnsureCreated();
// var rolmanager = services.GetRequiredService<RoleManager<Role>>();
// async Task CreateRoleIfNotExists(string roleName)
// {
// if (!await rolmanager.RoleExistsAsync(roleName))
// {
// await rolmanager.CreateAsync(new Role
// {
// Id = Ulid.NewUlid().ToString(),
// Name = roleName,
// CreatedTime = DateTime.Now
// });
// }
// }
// await CreateRoleIfNotExists(Role.Administrator);
// await CreateRoleIfNotExists(Role.Owner);
// await CreateRoleIfNotExists(Role.Customer);
//}
app.MapControllers();
app.Run();
UserandRoleclasses codeusing Domain.Entites;instead ofDomain.Entities.OnConfiguringlike it says here? learn.microsoft.com/en-us/ef/core/get-started/overview/… Or it could be that it's throwing an error because some other service registration is missing. Try running with verbosity turned on, see if it gives you more info.AddDbContexteither, which means there's no DbContext to create. There's probably an inner exception saying that egDbContextOptionsisn't registered. Both the project templates and all docs that show how to use EF Core with DI show the use ofAddDbContext