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

问题描述 投票:2回答:2

.net核心的一个美妙之处在于它非常模块化和可配置。

这种灵活性的一个关键方面是它通过接口利用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。所以,如果我有一个类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中删除服务?

c# asp.net-core .net-core ioc-container
2个回答
5
投票

您的代码不起作用,因为ServiceDescriptor类不会覆盖Equals,而ServiceDescriptor.Transient()会返回一个与集合中的实例不同的新实例。

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

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

2
投票

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

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

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

引用文档:

使用与IServiceCollection相同的服务类型删除descriptor中的第一个服务并添加到集合中。

© www.soinside.com 2019 - 2024. All rights reserved.