.net核心的一个美妙之处在于它非常模块化和可配置。
这种灵活性的一个关键方面是它通过接口利用IoC来注册服务。理论上,这允许用很少的努力用该服务的自定义实现替换默认的.net服务。
理论上这一切听起来都很棒。但我有一个真正的工作案例,我想用我自己的替换默认的.net核心服务,我无法弄清楚如何删除默认服务。
更具体地说,在Startup.cs ConfigureServices
方法中,当调用services.AddSession()
时,它会在代码后注册一个DistributedSessionStore
vai:
services.AddTransient<ISessionStore, DistributedSessionStore>();
我想用我自己创建的一个替换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中删除服务?
您的代码不起作用,因为ServiceDescriptor
类不会覆盖Equals
,而ServiceDescriptor.Transient()
会返回一个与集合中的实例不同的新实例。
您必须在集合中找到ServiceDescriptor
并将其删除:
var serviceDescriptor = services.First(s => s.ServiceType == typeof(ISessionStore));
services.Remove(serviceDescriptor);
我想知道,如果你不想使用默认实现,为什么还要调用AddSession()
?
无论如何,您可以尝试使用Replace
方法:
services.Replace(ServiceDescriptor.Transient<ISessionStore, RonsSessionStore>());
引用文档:
使用与
IServiceCollection
相同的服务类型删除descriptor
中的第一个服务并添加到集合中。