Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 280
RonC Avatar asked Mar 02 '17 20:03

RonC


2 Answers

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);
like image 170
Jakub Lortz Avatar answered Oct 01 '22 01:10

Jakub Lortz


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.

like image 38
Henk Mollema Avatar answered Oct 01 '22 01:10

Henk Mollema