如何从.net核心IoC容器中删除默认服务?

Ron*_*n C 3 c# ioc-container .net-core asp.net-core

.net核心的美丽之处之一是它非常模块化且可配置。

这种灵活性的一个关键方面是,它通常通过接口利用IoC来注册服务。从理论上讲,这可以用很少的精力用该服务的自定义实现替换默认的.net服务。

从理论上讲,这听起来很棒。但是我有一个实际的工作案例,我想用我自己的默认替换.net核心服务,但我不知道如何删除默认服务。

更具体地说,在Startup.cs ConfigureServices方法中,当services.AddSession()调用时,它将注册一个DistributedSessionStorevai以下代码:

 services.AddTransient<ISessionStore, DistributedSessionStore>();
Run Code Online (Sandbox Code Playgroud)

从源代码中可以看到:https : //github.com/aspnet/Session/blob/rel/1.1.0/src/Microsoft.AspNetCore.Session/SessionServiceCollectionExtensions.cs

我想用自己创建的ISessionStore替换它。因此,如果我有一个RonsSessionStore:ISessionStore要替换当前注册的ISessionStore的类,该怎么办?

我知道我可以ConfigureServices通过以下方法在Startup.cs 方法中注册ISessionStore :

 services.AddTransient<ISessionStore, RonsSessionStore>();
Run Code Online (Sandbox Code Playgroud)

但是,如何删除已经注册的DistributedSessionStore

我试图通过startup.cs ConfigureServices方法来完成此任务

 services.Remove(ServiceDescriptor.Transient<ISessionStore, DistributedSessionStore>());
Run Code Online (Sandbox Code Playgroud)

但它没有任何作用,并且DistributedSessionStore仍在IoC容器中。有任何想法吗?

如何ConfigureServices使用startup.cs方法从IoC删除服务?

Hen*_*ema 6

我在想,你为什么还要打电话 AddSession()如果您不想使用默认实现?

无论如何,您可以尝试使用该Replace方法:

services.Replace(ServiceDescriptor.Transient<ISessionStore, RonsSessionStore>());
Run Code Online (Sandbox Code Playgroud)

引用文档:

删除IServiceCollectiondescriptor集合中具有相同服务类型的第一个服务并添加到集合中。


Jak*_*rtz 5

您的代码无效,因为ServiceDescriptor该类未覆盖Equals,并ServiceDescriptor.Transient()返回了一个新实例,该实例不同于集合中的实例。

您必须ServiceDescriptor在集合中找到并将其删除:

var serviceDescriptor = services.First(s => s.ServiceType == typeof(ISessionStore));
services.Remove(serviceDescriptor);
Run Code Online (Sandbox Code Playgroud)