Skip to content
Latchkey

ASP.NET Core "No service for type ... has been registered" in CI

A call to GetRequiredService<T>() (or a scope resolution) asked the container for a type that was never registered, so it throws immediately. This differs from an activation error: here the resolution is explicit.

What this error means

The app or a test fails with "No service for type 'X' has been registered." right where it resolves a service from the provider, commonly during seeding, background work, or a test helper.

.NET
System.InvalidOperationException: No service for type
'MyApp.Data.AppDbContext' has been registered.
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService

Common causes

The type is resolved but never registered

Code calls GetRequiredService<AppDbContext>() but no AddDbContext<AppDbContext>() runs, so the container has nothing to return.

Resolved from the root provider before registration

A resolution happens before or outside the point where services are added, or from a provider built without the registration.

How to fix it

Register the service before resolving it

  1. Add the registration (for a DbContext, use AddDbContext) in Program.cs.
  2. Resolve inside a created scope, not from the root provider during startup.
  3. Confirm the registration runs in the environment where the resolution happens.
Program.cs
builder.Services.AddDbContext<AppDbContext>(o =>
    o.UseNpgsql(builder.Configuration.GetConnectionString("Default")));

Use TryGetService when a service is optional

If the service may legitimately be absent, resolve with GetService<T>() and null-check instead of GetRequiredService<T>().

How to prevent it

  • Register a DbContext with AddDbContext, not a bare AddScoped, so options are configured.
  • Resolve scoped services inside a scope, not from the root provider.
  • Validate the service provider on startup to catch unregistered types.

Frequently asked questions

What causes ""No service for type has been registered""?
Code calls GetRequiredService<AppDbContext>() but no AddDbContext<AppDbContext>() runs, so the container has nothing to return.
How do I fix "No service for type has been registered"?
Register the service before resolving it

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card