'How do I resolve an Entity Framework error creating the db context

I have created my first (Blazer) project with Entity Framework. I got enable-migrations and update-database to work. Now, I get the following build error:

Error while validating the service descriptor 'ServiceType: Timesheet.Models.DatabaseContext Lifetime: Singleton
ImplementationType: Timesheet.Models.DatabaseContext': Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[Timesheet.Models.DatabaseContext]' while attempting to activate 'Timesheet.Models.DatabaseContext'.

The error is thrown at this point:

enter image description here

I've tried reading the error multiple times but I'm not sure what it's referring to. I'm hoping someone can point me in the right direction. Here is the db service in my startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddScoped(p =>
           p.GetRequiredService<IDbContextFactory<DatabaseContext>>().CreateDbContext());
}

I just have no idea where to go next. Any suggestions are appreciated.

Edit 1: Adding the full Program.cs file

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
using Timesheet.Data;
using Timesheet.Models;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<DatabaseContext>();

// Add services to the container.
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddControllersWithViews()
    .AddMicrosoftIdentityUI();

builder.Services.AddAuthorization(options =>
{
    // By default, all incoming requests will be authorized according to the default policy
    options.FallbackPolicy = options.DefaultPolicy;
});

builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor()
    .AddMicrosoftIdentityConsentHandler();
//builder.Services.AddSingleton<WeatherForecastService>();

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<DatabaseContext>(options =>
    options.UseSqlServer(connectionString));

var app = builder.Build();


// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();


Solution 1:[1]

move your var app = builder.Build()line at the end of UseSqlServer line. first register all of your service then build the app.

Solution 2:[2]

If you see an error like

"Unable to resolve service for type"

you must search the given unresolved type.

Unresolved type means, your middleware cannot identify what is the type given to him.

In this example Your services are in wrong order. Your builder cannot identify what is "Timesheet.Models.DatabaseContext".

So the solution seems you must call builder.Build() operation after builder.Configuration().

I suppose it helps when you see the same error at other times.

Solution 3:[3]

I found the answer to my error (along with moving the builder.Build() as suggested above. I changed the db service builder to use the ContextFactory

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContextFactory<DatabaseContext>(options =>
    options.UseSqlServer(connectionString));

and removed this builder from higher up in my startup builder.Services.AddSingleton<DatabaseContext>();

I was trying to construct my startup from a combination of scaffolding from EF6 and copying a project that was built in EF5. I guess there are some diffs which I still need to study to understand.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Asif Rahman
Solution 2
Solution 3 Dharman