Support for AddScoped to be per function calls
See original GitHub issueWith ASP.Net Core, using the DI with AddScoped is understood that the lifetime is per request. With WebJobs 3.0, AddScoped behaves the same way as AddSingleton, which does not play well when using a DbContext. AddScoped should be per “request”, basically per function call. At least, provide some entry points to start/stop the scope properly. Right now, the JobActivator does not allow to do such a thing because it is created with the IHostedService, which has a lifetime of the app. The GetService() cannot be used with scoping either.
I have searched everywhere how to actually hook up the scoping properly, and either all the executors are sealed or internal. The only way to make this work is to create a scope in each of my function calls which defeat the purpose of dependency injection…
I could create a scope in the CustomJobActivator
, but it is not disposed properly.
Expected behavior
AddScoped<IMyService, MyService>()
should be per request when injected in the Function class.
Or, injecting my IMyService
in the method parameters could work as well.
Actual behavior
Everything is treated as Singleton scope.
Known workarounds
public class ContinuousMethods
{
private readonly IServiceProvider serviceProvider;
private readonly IMyService myService;
public ContinuousMethods(
IServiceProvider serviceProvider
// IMyService myService // I wish it were Scoped
)
{
this.serviceProvider = serviceProvider;
//this.myService = myService;
}
public async Task SendEmail(
[QueueTrigger("%AzureStorage:Queue:SendEmail%")] int emailId,
ILogger logger
// IMyService myService // Why not...? But we don't have a binder for this right now.
)
{
// Ugly workaround that I have to insert in all my functions.
using (var scope = serviceProvider.CreateScope())
using (var myService = scope.ServiceProvider.GetService<IMyService>())
{
await myService.SendEmailAsync(emailId);
}
}
}
Related information
WebJobs 3.0
Issue Analytics
- State:
- Created 5 years ago
- Reactions:19
- Comments:18 (2 by maintainers)
Top GitHub Comments
Any news on that? This issue is still present in
3.0.10
@fabiocavTo anybody interested, I have opened a bug, since people who have answers about this matter don’t seem to be following this bug.
https://github.com/Azure/azure-webjobs-sdk/issues/2173