Skip to main content

Fixed: "System.InvalidOperationException: The service collection cannot be modified because it is read-only" in ASP.NET Core

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

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:

Program.cs (as it was)
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:

Terminal
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:

Output
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

A macOS-style terminal window titled Terminal — SlowReport showing dotnet run with --no-launch-profile and --urls http://localhost:5310 ending at once with Unhandled exception. System.InvalidOperationException: The service collection cannot be modified because it is read-only, followed by a stack trace from ServiceCollection.ThrowReadOnlyException through Add, AddSingleton and Configure to 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:

FrameWhat it tells you
OptionsServiceCollectionExtensions.Configure[TOptions]My Configure call ran
ServiceCollectionServiceExtensions.AddSingletonConfigure 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:

HostApplicationBuilder.cs (.NET 10.0.15, excerpt)
_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:

Program.cs
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:

Terminal
dotnet run --no-launch-profile --urls http://localhost:5310
Output
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.

A macOS-style terminal window titled Terminal — SlowReport showing dotnet run with --no-launch-profile and --urls http://localhost:5310 starting normally: Now listening on http://localhost:5310, Application started. Press Ctrl+C to shut down, Hosting environment Production and the content root path, then Ctrl+C and Application is shutting down.

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​

MistakeWhat happensDo this instead
Adding or configuring a service after builder.Build()InvalidOperationException at startup, before the app listensPut every builder.Services call before builder.Build()
Reading only the first line of the errorThe message doesn't say which line of your code did itRead the at Program line at the bottom: it names your file and line

Troubleshooting​

SymptomLikely causeFix
The service collection cannot be modified because it is read-only when the app startsA 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 startsThe compiler can't see the order problem: the list refuses the change only when the code runsSame 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​