.NET DI: Unable to resolve service for type while attempting to activate
Read the two type names in order, then check registration, namespace and lifetime. Includes the scoped-into-singleton follow-on error.

Introduction & Quick Summary
Symptom. The host starts, the first request fails, and the exception names two types you have both written:
System.InvalidOperationException: Unable to resolve service for type
'Billing.Abstractions.IInvoiceStore' while attempting to activate
'Billing.Api.Controllers.InvoiceController'.
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities...In Development it often fails at startup, because scope validation is on; in Production the same bug waits until the first request and appears as a 500 with a stack trace in the log.
Cause. ActivatorUtilities walked the constructor of InvoiceController, asked the container for IInvoiceStore, and got nothing back. Either the registration was never made, it was made for a different type than the constructor asks for, or it was made after builder.Build() and the container was already snapshotted.
Fix. Register the type the constructor actually requests, before the host is built:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<IInvoiceStore, SqlInvoiceStore>();
// ... other registrations ...
var app = builder.Build();// or forward an interface to a concrete registration
builder.Services.AddScoped<SqlInvoiceStore>();
builder.Services.AddScoped<IInvoiceStore>(sp => sp.GetRequiredService<SqlInvoiceStore>());Then verify the wiring instead of guessing:
using (var scope = app.Services.CreateScope())
{
var store = scope.ServiceProvider.GetService<IInvoiceStore>();
Console.WriteLine(store is null ? "NOT REGISTERED" : store.GetType().FullName);
}Core Mechanics, Signatures & Reproducible Setup
The .NET container is a dictionary from service type to one or more descriptors, each with a lifetime and a factory. Resolution is exact: the requested type must be registered under that type. Interfaces are not inferred from implementations, and an open generic registration only satisfies closed requests of that generic.
Reproduce the failure in a console app, with no ASP.NET involved:
using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection();
services.AddScoped<SqlInvoiceStore>(); // concrete only
var provider = services.BuildServiceProvider(new ServiceProviderOptions
{
ValidateOnBuild = true,
ValidateScopes = true,
});
using var scope = provider.CreateScope();
try
{
var store = scope.ServiceProvider.GetRequiredService<IInvoiceStore>();
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex.Message);
// No service for type 'IInvoiceStore' has been registered.
}ValidateOnBuild = true turns a first-request failure into a startup failure, and it is what ASP.NET Core enables automatically in the Development environment. That difference in timing is why this bug is so often reported as "works locally, fails in production": locally the app refuses to start, so nobody deploys it.
Three registration forms that are easy to confuse:
// wrong: only the concrete type is known to the container
services.AddScoped<SqlInvoiceStore>();
// right for a constructor that asks for the interface
services.AddScoped<IInvoiceStore, SqlInvoiceStore>();
// open generic: satisfies IRepository<Order>, not IRepository<>
services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));// keyed services are a separate namespace of registrations
services.AddKeyedSingleton<IClock, SystemClock>("utc");
// a non-keyed constructor parameter cannot receive thisKey Comparison Table
| Constructor asks for | Registered as | Resolves |
|---|---|---|
IInvoiceStore | AddScoped<IInvoiceStore, SqlInvoiceStore>() | yes |
IInvoiceStore | AddScoped<SqlInvoiceStore>() | no |
SqlInvoiceStore | AddScoped<IInvoiceStore, SqlInvoiceStore>() | no |
IRepository<Order> | AddScoped(typeof(IRepository<>), typeof(EfRepository<>)) | yes |
IRepository | open generic registration | no |
IClock | AddKeyedSingleton<IClock, SystemClock>("utc") | no, needs [FromKeyedServices] |
IOptions<MailOptions> | Configure<MailOptions>(...) | yes |
IHttpContextAccessor | nothing | no, needs AddHttpContextAccessor() |
| Lifetime | Instance scope | Requesting it from a singleton |
|---|---|---|
AddSingleton | one per container | fine |
AddScoped | one per request scope | throws when ValidateScopes is on |
AddTransient | a new instance per resolve | fine, but state is not shared |
| keyed | per key | only through [FromKeyedServices] |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. The registration exists but in another collection
builder.Services is snapshotted by builder.Build(). A registration added afterwards is silently discarded, which is a common outcome of a refactor that moves Add* calls into a helper:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
builder.Services.AddScoped<IInvoiceStore, SqlInvoiceStore>(); // too late, ignored
app.MapControllers();
app.Run();// extension method, called once before Build()
public static IServiceCollection AddBilling(this IServiceCollection services)
{
services.AddScoped<IInvoiceStore, SqlInvoiceStore>();
services.AddScoped<IInvoiceService, InvoiceService>();
return services;
}In integration tests the same rule appears as ConfigureTestServices: it must run before the test host is created, not inside a test method after factory.CreateClient().
2. Namespace drift between interface and implementation
Two IInvoiceStore interfaces in different namespaces compile fine and never resolve. This is the hardest variant to see, because the registration looks correct when read in isolation:
dotnet build /warnaserror:CS0436 # surfaces type conflicts from duplicate definitions
grep -rn "interface IInvoiceStore" --include=*.cs .// Program.cs often shows the mismatch only through the using directives
using Billing.Abstractions; // the registered one
// controller file:
using Billing.Legacy.Abstractions; // the requested one3. IHttpContextAccessor and other opt-in services
Some framework services are not registered by default. IHttpContextAccessor needs its own call, and a library that requires it usually ships an extension method for exactly this reason:
builder.Services.AddHttpContextAccessor();The lesson generalises: when the type comes from a package, look for the package's registration method before writing one by hand.
4. Scoped into singleton, the follow-on error
Registering the missing service as scoped and injecting it into a singleton produces a second InvalidOperationException: Cannot consume scoped service 'IInvoiceStore' from singleton 'ReportScheduler'. The fix is structural, not a cast:
// a singleton that needs scoped work takes the factory
public sealed class ReportScheduler(IServiceScopeFactory scopeFactory) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var scope = scopeFactory.CreateScope();
var store = scope.ServiceProvider.GetRequiredService<IInvoiceStore>();
await store.PurgeAsync(stoppingToken);
}
}IServiceScopeFactory, IDbContextFactory<T>, or an explicitly scoped unit of work are the three supported answers; BuildServiceProvider() inside a singleton is not.
5. Options and the two error directions
IOptions<T> requires Configure<T>; T itself requires AddOptions<T>().Bind(...). Asking for the wrong one produces the same "unable to resolve" text with a framework type:
builder.Services.Configure<MailOptions>(builder.Configuration.GetSection("Mail"));
// consumer
public sealed class Mailer(IOptions<MailOptions> options) { }Validating options at startup turns a misconfiguration into a clear failure instead of a null field: builder.Services.AddOptions<MailOptions>().Bind(...).ValidateDataAnnotations().ValidateOnStart().
6. Listing what is actually registered
When the registration looks right and the exception persists, print the descriptors. This catches the namespace case, the double registration, and the "registered the wrong lifetime" case in one step:
foreach (var d in builder.Services.Where(d => d.ServiceType.Name.Contains("Invoice")))
{
Console.WriteLine($"{d.Lifetime}: {d.ServiceType.FullName} -> {d.ImplementationType?.FullName}");
}// and once, at startup, in every environment
builder.Host.UseDefaultServiceProvider(o =>
{
o.ValidateOnBuild = true;
o.ValidateScopes = true;
});Common Compilation/Runtime Mistakes & Version Gotchas
- Registering the concrete type while injecting the interface. The container does no inference.
- Adding registrations after
builder.Build(). They are discarded. - Assuming
AddControllersalso registers your services. It registers framework services only. - Mixing two interfaces with the same name from different namespaces.
- Injecting a scoped service into a singleton. The follow-on error appears later and reads differently.
- Requesting a keyed service without
[FromKeyedServices]. - Expecting
IOptions<T>to resolveT. They are different service types. - Relying on Production's permissive behaviour. The bug is real; Production just delays the failure.
Confirm the configuration values the services read with the JSON formatter, and when two environments behave differently, compare their appsettings*.json with the text diff tool.
Reference: Dependency injection in .NET, DI guidelines, and ActivatorUtilities.
Official references
primary documentationThe C# documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related C# guides
All C# guidesC# await vs Task.Result: Avoid Blocking Async Code
c# await vs task result: Understand the difference between await and Task.Result in C#, why blocking on async tasks can cause deadlocks, and when it's acceptable.
System.Text.Json: The JSON value could not be converted to a type
The serializer refuses to coerce. Read the exception path, then add a converter for dates, number handling for quoted values, or an enum converter.
NuGet NU1101: unable to find the package in any source
The package is not on any feed this solution queries. Check the inherited source list first, then authentication.
dotnet: A compatible .NET SDK was not found (global.json)
The message names the file and the missing band. Relax rollForward, pin an installed version, or remove the second pin in CI.
More in C#
All C# guidesThe guides filed next to this one in C#, in library order.