InvalidOperationException 🟪 .NET

InvalidOperationException: Unable to resolve service for type 'X' while attempting to activate 'Y'

ASP.NET Core’s dependency injection container can’t build Y because one of its constructor dependencies (X) was never registered.

Seen on: .NET

Meaning

Every constructor parameter of a controller/service must be registered in builder.Services. The message names both the missing type and the class that needs it.

Common causes

  • Service not registered (AddScoped<IMailer, Mailer>() missing)
  • Registered the concrete type but injecting the interface (or vice versa)
  • DbContext not added with AddDbContext
  • Scoped service injected into a singleton (different error, same area)

⚡ Quick fix

  1. Register the missing type in Program.cs
  2. Inject the same type you registered (interface vs class)
  3. Use AddDbContext<AppDbContext>(…) for EF Core contexts

Detailed fix by platform

.NET

  1. Program.cs registrations:
    csharp
    builder.Services.AddDbContext<AppDbContext>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("Default")));
    builder.Services.AddScoped<IEmailSender, SmtpEmailSender>();
    builder.Services.AddHttpClient<IWeatherClient, WeatherClient>();

How to diagnose

  1. Missing type — Which type X is named?
  2. Registration — Is X registered — same interface/class?
  3. Lifetime — Any scoped-into-singleton issues?

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.