在AzureFunction中注入EntityFrameworkCore DbContext

时间:2018-05-24 08:43:02

标签: dependency-injection azure-functions

我有像

这样的解决方案

ABC.Domain(.net standard 2.0)

ABC.Service(.net standard 2.0 + EFCore + EFCoreSQL)

ABC.AzureFunction(.net standard 2.0)v2

ABC.Web(.net core 2.0)

我在ABC.Service中使用UnitOfWork和Repository模式,并使用.net核心原生DI扩展注入。它正在Web项目中工作,但我无法在Azure Functions中解析DbContext引用。

ABC.Web(它正在工作)

Startup.cs

services.AddEntityFrameworkSqlServer()
.AddDbContext<AnimalHubContext>(o =>
{
o.UseSqlServer(this.Configuration["Data:ConnectionString"]);
});
services.AddScoped<IAccountRepository, AccountRepository>();
        services.AddScoped<IUnitOfWork, UnitOfWork>();
        services.AddSingleton<IAppConfigurationManager, AppConfigurationManager>();
        services.AddSingleton<ICachingService, CachingService>();
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddScoped<ABCContext>();

ABC.AzureFunction

AzureFunction DI

public static async Task RunAsync([QueueTrigger("analyzeimage",
        Connection = "animalhubnonblob_STORAGE")]string myQueueItem,
        TraceWriter log,
        [Inject(typeof(IUnitOfWork))]IUnitOfWork uow)

InjectConfiguration.cs

private void RegisterServices(IServiceCollection services)
    {
        string connectionString = "****************";
        services.AddEntityFrameworkSqlServer()
                .AddDbContext<AnimalHubContext>((serviceProvider, options)>
                 options.UseSqlServer(connectionString)
                .UseInternalServiceProvider(serviceProvider));

        services.AddScoped<ABCContext>();
        services.AddScoped<IAccountRepository, AccountRepository>();
        services.AddScoped<ICategoryRepository, CategoryRepository>();
        services.AddScoped<IUnitOfWork, UnitOfWork>();
    }

错误 System.Private.CoreLib:执行functio时出现异常 n:AnalyzeImageFunction。 Microsoft.Azure.WebJobs.Host:异常绑定参数&#39; uow&#39;。 Microsoft.Extensions.DependencyInjection:无法解析作用域服务&#39; AnimalHub.Persistence.IUnitOfWork&#39;来自root provider。

0 个答案:

没有答案