Deleting a Service in ASP.Net Core Dependency Injection

In Core Asp.Net MVC (early, version 1.0 or 1.1), injection dependency bindings are configured as follows in the Startup.cs class:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddScoped<IMyService, MyService>();
        // ...
    }
}

      

In my applications, I usually have a base startup class where general bindings are defined as a sequence of these lines:

public abstract class BaseStartup
{
    public virtual void ConfigureServices(IServiceCollection services)
    {
        services.AddScoped<IMyService1, MyService1>();
        services.AddScoped<IMyService2, MyService2>();
    }
}

      

Then, in my application, I inherit the startup class and inject other services:

public class Startup : BaseStartup
{
    public override void ConfigureServices(IServiceCollection services)
    {
        base.ConfigureServices(services);

        services.AddScoped<IMyService3, MyService3>();
        services.AddScoped<IMyService4, MyService4>();
    }
}

      

Now I am wondering: how can I "override" the previous binding? I would like, for example, to either remove or change the binding defined in the base class, for example:

services.Remove<IMyService1>(); // Doesn't exist
services.AddScoped<IMyService1, MyBetterService1>();

      

Or just update the binding:

services.AddScoped<IMyService1, MyBetterService1>(replacePreviousBinding: true); // Doesn't exist either !

      

Is there a way to do this? Or maybe just declaring a new binding with the same interface as the previously defined binding will override that binding?

+3


source to share


1 answer


You can use the regular collection API to remove your services:

services.AddScoped<IService>();

var serviceDescriptor = services.FirstOrDefault(descriptor => descriptor.ServiceType == typeof(IService));
services.Remove(serviceDescriptor);

      



Also you can create extension methods to achieve the same:

public static class ServiceCollectionExtensions
{
    public static IServiceCollection Remove<T>(this IServiceCollection services)
    {
        var serviceDescriptor = services.FirstOrDefault(descriptor => descriptor.ServiceType == typeof(T));
        if (serviceDescriptor != null) services.Remove(serviceDescriptor);

        return services;
    }
}

      

+8


source







All Articles