Ask Your Question
4

How can the ServiceCollection be overridden in middleware?

asked 2022-08-30 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-07-28 14:00:00 +0000

plato gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-08-30 11:00:00 +0000

Seen: 16 times

Last updated: Jul 28 '21