Remove a service in ASP.Net Core Dependency Inject

2020-06-09 01:52发布

In an Asp.Net MVC Core (early versions, versions 1.0 or 1.1), dependency injection bindings are configured as follow 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 generic 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 as well :

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

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

I now wonder : how can I kind of 'override' a previous binding ? I would like, for instance, to either remove, or modify a binding defined in the base class, like :

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

Or simply update the binding :

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

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

1条回答
神经病院院长
2楼-- · 2020-06-09 02:24

You can use normal 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;
    }
}
查看更多
登录 后发表回答