Let us consider a service registration in Startup.ConfigureServices
:
public void ConfigureServices(IServiceCollection services)
{
services.A
Just to add on @ilya-chumakov 's great answer, here is the same method but with support for implementation factories
public static IServiceCollection Replace(
this IServiceCollection services,
Func implementationFactory,
ServiceLifetime lifetime)
where TService : class
{
var descriptorToRemove = services.FirstOrDefault(d => d.ServiceType == typeof(TService));
services.Remove(descriptorToRemove);
var descriptorToAdd = new ServiceDescriptor(typeof(TService), implementationFactory, lifetime);
services.Add(descriptorToAdd);
return services;
}
in case we want to use it with a factory that instantiates the service like the following sample:
var serviceProvider =
new ServiceCollection()
.Replace(sp => new MyService(), ServiceLifetime.Singleto)
.BuildServiceProvider();