在ASP.Net Core依赖注入中删除服务 [英] Remove a service in ASP.Net Core Dependency Injection

查看:565
本文介绍了在ASP.Net Core依赖注入中删除服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Asp.Net MVC Core(早期版本,版本1.0或1.1)中,依赖项注入绑定在Startup.cs类中的配置如下:

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>();
        // ...
    }
}

在我的应用程序中,我通常有一个基本的Startup类,其中通用绑定定义为这些行的序列:

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>();

或者只是更新绑定:

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 ?

推荐答案

您可以使用普通的集合API删除服务:

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;
    }
}

这篇关于在ASP.Net Core依赖注入中删除服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆