Regardless of whether we should, can we use IHostedService
in an Azure Functions App?
Here is an attempt to register a hosted service (background service, specifically) as IHostedService
:
internal sealed class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddHostedService<ExampleBackgroundService>();
}
}
The Functions App then throws the following exception:
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'
No, this is not currently possible. There is some discussion on this 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)
The rest of the thread has more details and is worth checking out for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With