System.invalidoperationexception: ‘cannot modify servicecollection after application is built.’

system.invalidoperationexception: ‘cannot modify servicecollection after application is built.’

When you encounter the “InvalidOperationException” with the message “cannot modify ServiceCollection after application is built”, it means that you are trying to modify the service collection or the dependency injection container after it has been used to build the application.

In .NET Core, the service collection is typically modified in the “ConfigureServices” method of the “Startup” class. This method is called during application startup and is responsible for configuring the services that the application will use. Once the application has been built, any further modification to the service collection is not allowed.

To resolve this issue, you need to ensure that all necessary services are registered in the “ConfigureServices” method before building the application. Here’s an example:

public void ConfigureServices(IServiceCollection services)
{
    // Register services needed by the application
    services.AddSingleton<ILogger, Logger>();
    services.AddScoped<IUserService, UserService>();
    // Add other services...

    // Build the application with the registered services
    var serviceProvider = services.BuildServiceProvider();

    // Resolve and use the services as needed
    var userService = serviceProvider.GetService<IUserService>();
    userService.DoSomething();
}

In the example above, we register two services (ILogger and IUserService) in the “ConfigureServices” method. After building the application with the registered services, we can then resolve and use these services as needed.

It’s important to note that modifying the service collection after the application is built is not encouraged because it can lead to unexpected behavior or runtime errors. Therefore, it’s recommended to register all necessary services before building the application.

Related Post

Leave a comment