0

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();
3
  • 1
    Don't build your app until after you've registered your services. Commented Feb 11, 2022 at 0:36
  • ok, but I don't understand how to fix it. Can you give me an example? Commented Feb 11, 2022 at 1:13
  • 1
    As he said, you have a .Services.Add... call after .Build(). Fix that first, it's likely to be the cause of your problem. Commented Feb 11, 2022 at 1:56

3 Answers 3

1

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

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

Comments

1

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.

1 Comment

Thanks Muhammed, I appreciate the explanation. I've never set up the framework like this so thanks for your patience. As you suggested, I moved the builder after the build.configuration but I get the same error. I added the full Program.cs file in case there is something else that jumps out.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.