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

How to remove a default service from the .net core IoC container?

.net core 的优点之一是它非常模块化和可配置。

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

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

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

 services.AddTransient<ISessionStore, DistributedSessionStore>();

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

我想用我自己创建的一个替换那个 ISessionStore。那么如果我有一个 class RonsSessionStore:ISessionStore 想用来替换当前注册的 ISessionStore,我该怎么做呢?

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

 services.AddTransient<ISessionStore, RonsSessionStore>();

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

我试图通过

在 startup.cs ConfigureServices 方法中完成此操作
 services.Remove(ServiceDescriptor.Transient<ISessionStore, DistributedSessionStore>());

但它没有任何效果,DistributedSessionStore 仍在 IoC 容器中。有任何想法吗?

如何在 startup.cs 的 ConfigureServices 方法中从 IoC 中删除一项服务?

您的代码不起作用,因为 ServiceDescriptor class 不会覆盖 Equals,并且 ServiceDescriptor.Transient() returns 是一个新实例,不同于collection.

中的那个

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

var serviceDescriptor = services.First(s => s.ServiceType == typeof(ISessionStore));
services.Remove(serviceDescriptor);

我想知道,如果您不想使用默认实现,为什么还要调用 AddSession()

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

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

引用文档:

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