Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The ServiceCollection in middleware can be overridden by creating a new instance of it in the Configure method of your Startup.cs class. This new instance can be populated with your own services that will replace the default implementation. For example:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    var serviceCollection = new ServiceCollection();

    // Register your own services here
    serviceCollection.AddTransient<IMyService, MyService>();

    // Replace the default services with your own
    app.ApplicationServices = serviceCollection.BuildServiceProvider();

    app.UseMiddleware<MyMiddleware>();
}

Note that the ApplicationServices property of the app parameter is being set to the new ServiceProvider created from the ServiceCollection. This will ensure that any service resolution inside the middleware pipeline will use the new service instances instead of the defaults.