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.
System.InvalidOperationException: No service for type
'MyApp.Data.AppDbContext' has been registered.
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredServiceCommon 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
- Add the registration (for a DbContext, use
AddDbContext) inProgram.cs. - Resolve inside a created scope, not from the root provider during startup.
- Confirm the registration runs in the environment where the resolution happens.
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.