1

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();
5
  • Most of the text of your question is expressing frustration rather than adding useful details to your question. e.g.: "I've been trying to fix this error for the past week"; "I haven't been able to solve it"; "I think all the code I wrote is correct, but I'm still getting this error". Commented Nov 14 at 16:13
  • Please provide User and Role classes code Commented Nov 14 at 16:16
  • I know its nitpicking but one of your usings is using Domain.Entites; instead of Domain.Entities. Commented Nov 14 at 16:22
  • The error is saying it can't even instantiate your AppDbContext. So it's nothing to do with your entities. It probably can't create a DbContextOptions - have you overridden OnConfiguring like 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. Commented Nov 14 at 18:37
  • The full exception is missing so we can't guess what throws or where. There's no AddDbContext either, which means there's no DbContext to create. There's probably an inner exception saying that eg DbContextOptions isn't registered. Both the project templates and all docs that show how to use EF Core with DI show the use of AddDbContext Commented Nov 15 at 11:02

1 Answer 1

4

I don't see AddDbContext (or similar) in your code, so try adding it. For example:

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(connString)); // change call to Use{DbType} according to your needs

See the Configure Identity services section of the Introduction to Identity on ASP.NET Core doc.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.