How to remove a default service from the .net core

2020-04-06 03:35发布

One of the beautiful things about .net core is that it is very modular and configurable.

A key aspect of that flexibility is that it leverages an IoC for registering services, often via interfaces. This in theory allows for replacing a default .net service with a custom implementation of that service with very little effort.

This all sounds awesome in theory. But I have a real work case where I want to replace a default .net core service with my own and I can't figure out how to remove the default service.

More specifically, in the Startup.cs ConfigureServices method, when services.AddSession() is called it registers a DistributedSessionStore vai following code:

 services.AddTransient<ISessionStore, DistributedSessionStore>();

as can be seen in the source code: https://github.com/aspnet/Session/blob/rel/1.1.0/src/Microsoft.AspNetCore.Session/SessionServiceCollectionExtensions.cs

I'd like replace that ISessionStore with one of my own creation. So if I have a class RonsSessionStore:ISessionStore that I want to use to replace the currently registered ISessionStore, how can I do it?

I know I can register my ISessionStore in the Startup.cs ConfigureServices method via the following:

 services.AddTransient<ISessionStore, RonsSessionStore>();

But how can I remove the already registered DistributedSessionStore?

I tried to accomplish this in the startup.cs ConfigureServices method via

 services.Remove(ServiceDescriptor.Transient<ISessionStore, DistributedSessionStore>());

but it had no effect and the DistributedSessionStore was still in the IoC container. Any ideas?

How does one remove a service from the IoC in the ConfigureServices method of the startup.cs?

2条回答
我欲成王,谁敢阻挡
2楼-- · 2020-04-06 03:44

I'm wondering, why would you still call AddSession() if you do not want to use the default implementation?

Anyway, you can try and use the Replace method for this:

services.Replace(ServiceDescriptor.Transient<ISessionStore, RonsSessionStore>());

Quoting the docs:

Removes the first service in IServiceCollection with the same service type as descriptor and adds to the collection.

查看更多
在下西门庆
3楼-- · 2020-04-06 03:59

Your code doesn't work because the ServiceDescriptor class doesn't override Equals, and ServiceDescriptor.Transient() returns a new instance, different than the one in the collection.

You would have to find the ServiceDescriptor in the collection and remove it:

var serviceDescriptor = services.First(s => s.ServiceType == typeof(ISessionStore));
services.Remove(serviceDescriptor);
查看更多
登录 后发表回答