WebJobs 3.0 Dependency Injection AddScoped per function call

1.1k views Asked by At

With WebJobs 3.0, they propose to use the Dependency Injection via ConfigureServices()

However, the services added with AddScoped() are behaving the exact same way as AddSingleton(): they are configured for the lifetime of the WebJob. I would prefer to have it scoped per function call. How can we achieve this?

I tried to use my custom job activator and do something like this:

public T CreateInstance<T>()
{
    using (var scope = _service.CreateScope())
    {
        var service = scope.ServiceProvider.GetService<T>();

        return service;
    }
}

However, this gives me the following error: The operation cannot be completed because the DbContext has been disposed. The initialization is disposed before any call is made. I can't find how to connect this scoping mechanism properly.

The goal is to do have scoped dependency per function. At the moment, this is the only work around found to fix this issue.

public async Task SendEmail(
    [QueueTrigger("%AzureStorage:Queue:SendEmail%")] int emailId,
    ILogger logger
)
{
    // 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);
    }
}
0

There are 0 answers