Asp.net core 如何添加通用后台服务

Asp.net core 如何添加通用后台服务,asp.net-core,Asp.net Core,如何在asp.NET 2.2中添加通用后台服务 public class TestBackgroundService<T> : BackgroundService { private ICustomClass<T> _customClass = new CustomClass<T>(); public TestBackgroundService(ICustomClass<T> customClass) {

如何在asp.NET 2.2中添加通用后台服务

public class TestBackgroundService<T> : BackgroundService
{
    private ICustomClass<T> _customClass = new CustomClass<T>();

    public TestBackgroundService(ICustomClass<T> customClass)
    {
        _customClass = customClass;
    }
    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        throw new NotImplementedException();
    }
}

public class CustomClass<T> : ICustomClass<T>
{
}

public interface ICustomClass<T>
{
}

public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton(typeof(ICustomClass<>), typeof(CustomClass<>));
        services.AddHostedService<TestBackgroundService<>>(); // THIS LINE DOESN'T COMPILE

    }

}
公共类TestBackgroundService:BackgroundService
{
私有ICustomClass_customClass=新customClass();
公共TestBackgroundService(ICustomClass customClass)
{
_customClass=customClass;
}
受保护的覆盖任务ExecuteAsync(CancellationToken stoppingToken)
{
抛出新的NotImplementedException();
}
}
公共类CustomClass:ICustomClass
{
}
公共接口ICustomClass
{
}
公营创业
{
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
AddSingleton(typeof(ICustomClass)、typeof(CustomClass));
services.AddHostedService();//此行未编译
}
}

你应该问问自己,一个通用的后台服务应该做什么?如果不指定
t
,那么它应该如何工作

没有指定类型参数的泛型类只是类的“模板”,不能实例化。您必须理解,只有通过指定类型参数,泛型类型才真正成为可以使用和实例化的具体类型。这也意味着有无限多的潜在类型源自泛型类型


因此,当您考虑后台服务时,框架应该为您选择什么类型的参数?都是吗?然后会有无限量的后台服务,应用程序永远无法启动。或者只是其中的一部分?在这种情况下,您可以指定要使用哪些具体类型参数,并分别注册这些后台服务。

您应该问问自己,通用后台服务应该做什么?如果不指定
t
,那么它应该如何工作

没有指定类型参数的泛型类只是类的“模板”,不能实例化。您必须理解,只有通过指定类型参数,泛型类型才真正成为可以使用和实例化的具体类型。这也意味着有无限多的潜在类型源自泛型类型

因此,当您考虑后台服务时,框架应该为您选择什么类型的参数?都是吗?然后会有无限量的后台服务,应用程序永远无法启动。或者只是其中的一部分?在这种情况下,将由您指定要使用的具体类型参数,并分别注册这些后台服务