IHostedService 可用于 Azure Functions 应用程序吗?

IHostedService usable in Azure Functions App?

无论我们是否应该,我们可以在 Azure Functions 应用程序中使用 IHostedService 吗?

这是尝试将托管服务(特别是后台服务)注册为 IHostedService:

internal sealed class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        builder.Services.AddHostedService<ExampleBackgroundService>();
    }
}

Functions 应用随后抛出以下异常:

Microsoft.Azure.WebJobs.Script.InvalidHostServicesException: 'The following service registrations did not match the expected services:
  [Invalid] ServiceType: Microsoft.Extensions.Hosting.IHostedService, Lifetime: Singleton, ImplementationType: ExampleBackgroundService'

不,这目前不可能。对此有一些讨论 GitHub issue:

This would not play well with the dynamic scaling infrastructure. The scale controller is not aware of any logic running outside of the context of a function execution, and may scale in if it believes an application is idle. Customers would not have a reliable mechanism to keep that running unless they're artificially triggering function executions, and this would certainly generate confusion and support cases.

The runtime and Functions infrastructure is not setup for compute use outside of the context of a function. Allowing the registration of custom hosted services would expose a feature that enables that, which would not play well with other infrastructure components (including fraud detection which could severely impact a customer's application)

线程的其余部分有更多详细信息,值得查看以获取更多信息。