Fixed: "System.InvalidOperationException: The service collection cannot be modified because it is read-only" in ASP.NET Core
My ASP.NET Core app stopped before it listened on anything, with System.InvalidOperationException: The service collection cannot be modified because it is read-only. The stack trace pointed at a builder.Services.Configure call that I had put after builder.Build(). Build() locks the list of services, so every registration has to come before it.
What I Was Doing
I was giving a small ASP.NET Core app a longer shutdown timeout, so that a request still running when the app stops gets time to finish. The app, SlowReport, has one endpoint, /report, which takes 40 seconds to answer. The setting is one call on builder.Services, and I added it below the line that builds the app:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
builder.Services.Configure<HostOptions>(options =>
{
options.ShutdownTimeout = TimeSpan.FromSeconds(60);
});
app.MapGet("/report", async () =>
{
app.Logger.LogInformation("Report started.");
await Task.Delay(TimeSpan.FromSeconds(40));
app.Logger.LogInformation("Report finished.");
return "Your report is ready.";
});
app.Run();
Then I started it from the project folder:
dotnet run --no-launch-profile --urls http://localhost:5310
dotnet run builds the app and starts it. --no-launch-profile skips the settings in Properties/launchSettings.json, and --urls sets the address the app listens on.
What I Expected
The app to start as it did before the change: print Now listening on: http://localhost:5310 and Application started. Press Ctrl+C to shut down., then wait for requests, now with a 60-second shutdown timeout.
What I Got
It stopped before it listened on anything:
Unhandled exception. System.InvalidOperationException: The service collection cannot be modified because it is read-only.
at Microsoft.Extensions.DependencyInjection.ServiceCollection.ThrowReadOnlyException()
at Microsoft.Extensions.DependencyInjection.ServiceCollection.System.Collections.Generic.ICollection<Microsoft.Extensions.DependencyInjection.ServiceDescriptor>.Add(ServiceDescriptor item)
at Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(IServiceCollection services, Type serviceType, Object implementationInstance)
at Microsoft.Extensions.DependencyInjection.OptionsServiceCollectionExtensions.Configure[TOptions](IServiceCollection services, String name, Action`1 configureOptions)
at Program.<Main>$(String[] args) in /Users/you/source/SlowReport/Program.cs:line 4

What I Checked
The last line of the stack trace names the line in my own code: Program.cs:line 4, the builder.Services.Configure<HostOptions> call. The lines above it are inside .NET, and they read from the bottom up:
| Frame | What it tells you |
|---|---|
OptionsServiceCollectionExtensions.Configure[TOptions] | My Configure call ran |
ServiceCollectionServiceExtensions.AddSingleton | Configure adds a registration to the list of services |
The frame that ends in .Add(ServiceDescriptor item) | Adding that registration called the list's Add |
ServiceCollection.ThrowReadOnlyException() | The list refused it, because it is read-only |
Microsoft's API reference. builder.Services is a ServiceCollection, and its MakeReadOnly method does what the message says: After the collection is marked as read-only, any further attempt to modify it throws an InvalidOperationException.
Where it becomes read-only. ASP.NET Core and .NET are open source. In version 10.0.15, the one that ran here, WebApplicationBuilder.cs builds the app by calling the generic host builder's Build(), and HostApplicationBuilder.cs ends that method like this:
_appServices = _createServiceProvider();
// Prevent further modification of the service collection now that the provider is built.
_serviceCollection.MakeReadOnly();
return HostBuilder.ResolveHost(_appServices, diagnosticListener);
Why It Happens
builder.Build() turns the list of registered services into the app's service provider, the object that hands services to the app while it runs. Right after that, it marks the list read-only, as the comment in the source says, because the provider is already built from it. Any change to builder.Services after Build() is refused with this exception, so the app ended at line 4 and never reached app.Run().
The Fix
Move the call above var app = builder.Build();, where every change to builder.Services belongs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<HostOptions>(options =>
{
options.ShutdownTimeout = TimeSpan.FromSeconds(60);
});
var app = builder.Build();
app.MapGet("/report", async () =>
{
app.Logger.LogInformation("Report started.");
await Task.Delay(TimeSpan.FromSeconds(40));
app.Logger.LogInformation("Report finished.");
return "Your report is ready.";
});
app.Run();
The order in Program.cs is: create the builder, register and configure services, build the app, then map endpoints and run.
After the Fix
The same command:
dotnet run --no-launch-profile --urls http://localhost:5310
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5310
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
Content root path: /Users/you/source/SlowReport
^Cinfo: Microsoft.Hosting.Lifetime[0]
Application is shutting down...
The app started and waited for requests. ^C is how the terminal shows Ctrl+C, which I pressed to stop it.

What the setting itself does, with a 40-second request that finishes after Ctrl+C, is in How to Let Requests Finish When an ASP.NET Core App Shuts Down (C#).
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Adding or configuring a service after builder.Build() | InvalidOperationException at startup, before the app listens | Put every builder.Services call before builder.Build() |
| Reading only the first line of the error | The message doesn't say which line of your code did it | Read the at Program line at the bottom: it names your file and line |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
The service collection cannot be modified because it is read-only when the app starts | A change to builder.Services runs after builder.Build() | Move the line that the at Program frame names above builder.Build() |
| The app builds without errors but fails when it starts | The compiler can't see the order problem: the list refuses the change only when the code runs | Same fix: the order of the calls, not their syntax |
FAQ
Does this happen only with Configure?
No. Microsoft's reference says that once the collection is read-only, any further attempt to modify it throws an InvalidOperationException. Configure failed here in the list's Add, the same method that AddSingleton calls in the stack trace.
Why didn't the compiler catch it?
builder.Services is still an ordinary property after Build(), so the call compiles. The list only refuses the change while the app runs.
Can a service be added after the app is built?
Not to builder.Services: Build() locks it. Register everything the app needs before that line.
Conclusion
The service collection cannot be modified because it is read-only means a change to builder.Services ran after builder.Build(). The last line of the stack trace names that line. Move it above Build(), and the app starts.
Additional Resources
- ServiceCollection.MakeReadOnly — the method that locks the list, and the exception it causes.
- WebApplicationBuilder.Services — the services collection you add to before
Build(). - HostApplicationBuilder.cs at v10.0.15 — where
Build()callsMakeReadOnly.
