You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Azure Function中注入EntityFrameworkCore DbContext遇依赖解析问题

Fixing "Cannot resolve scoped service from root provider" in Azure Functions

The error you're seeing happens because you're trying to resolve a scoped service (IUnitOfWork) from the root service provider in a static function. Azure Functions creates a dedicated scope per function execution, and scoped services can't be accessed directly from the root (singleton) provider. Here's how to fix this step by step:

Step 1: Convert Your Function Class to Non-Static

Static functions can't use constructor injection, which is the correct way to access scoped services in Azure Functions. Update your function class to remove the static modifier and use constructor injection instead of the [Inject] attribute:

public class AnalyzeImageFunction
{
    private readonly IUnitOfWork _uow;

    // Inject IUnitOfWork via constructor (resolves within the execution scope)
    public AnalyzeImageFunction(IUnitOfWork uow)
    {
        _uow = uow;
    }

    public async Task RunAsync([QueueTrigger("analyzeimage", Connection = "animalhubnonblob_STORAGE")]string myQueueItem, TraceWriter log)
    {
        log.Info($"Processing queue item: {myQueueItem}");
        
        // Use your scoped IUnitOfWork instance here
        // Example: var account = await _uow.AccountRepository.GetByIdAsync(1);
    }
}

Step 2: Correct Service Registration in Your Startup Class

Ensure your DI configuration uses the Azure Functions-specific IWebJobsBuilder and properly registers scoped services. Also, avoid hardcoding connection strings—use the configuration system for portability:

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using System.IO;

[assembly: WebJobsStartup(typeof(ABC.AzureFunction.InjectConfiguration))]
namespace ABC.AzureFunction
{
    public class InjectConfiguration : IWebJobsStartup
    {
        public void Configure(IWebJobsBuilder builder)
        {
            // Build configuration to access app settings
            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables()
                .Build();

            // Register DbContext with scoped lifetime (default for AddDbContext)
            builder.Services.AddDbContext<AnimalHubContext>(options =>
                options.UseSqlServer(configuration["Data:ConnectionString"]));

            // Register all scoped services
            builder.Services.AddScoped<ABCContext>();
            builder.Services.AddScoped<IAccountRepository, AccountRepository>();
            builder.Services.AddScoped<ICategoryRepository, CategoryRepository>();
            builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();
        }
    }
}

Why This Resolves the Error

  • Non-Static Class: Azure Functions creates a new instance of your function class for each execution, ensuring scoped services are tied to the correct execution context.
  • Constructor Injection: Services are resolved within the function's dedicated scope, not the root provider—this matches how scoped services work in ASP.NET Core.
  • Proper Configuration: Using the built-in configuration system ensures your connection string works both locally (via local.settings.json) and in Azure (via app settings).

Additional Tips

  • Make sure your local.settings.json includes the Data:ConnectionString entry when testing locally.
  • For Azure deployment, add the connection string as an application setting in the Function App portal.
  • Avoid using the [Inject] attribute for scoped services in static functions—it bypasses the execution scope and leads to the root provider error.

内容的提问来源于stack exchange,提问作者Pankaj Rawat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:03:41