【问题标题】:How to use dependency injection in Azure Durable Functions?如何在 Azure Durable Functions 中使用依赖注入?
【发布时间】:2021-06-25 09:14:24
【问题描述】:

我想创建一个 Azure 持久函数,该函数将从 Internet 下载 CSV,并根据此文件中的数据,使用 EntityFramework 更新我的数据库。

我设置了使用 TimeTrigger 触发的简单启动功能。该函数负责启动编排器。编排器并行执行多个活动。大约有 40000 个工作项要处理,这就是编排器触发的活动的数量。其中一些活动将需要更新数据库(插入/更新/删除行)。为此,我需要一个数据库连接。我可以通过以下方式在 StartUp 中配置 DI:

public override void Configure(IFunctionsHostBuilder builder)
        {
            var connectionString = Environment.GetEnvironmentVariable("DefaultConnection");
            builder.Services.AddDbContext<SqlContext>(options => options.UseSqlServer(connectionString));
            builder.Services.AddScoped<IDbContext, SqlContext>();
        }
    }

但是,我的所有功能(协调器、活动功能等)都是静态的,并且驻留在静态类中。我没有看到任何在非静态类中定义持久函数的例子,当我自己尝试时遇到了各种各样的问题,所以我认为它们必须是静态的,而不需要过多地研究它。

我不知道如何将我的DbContext 对象传递给Activity 函数,以便它可以在需要时更新数据库中的数据。

我应该如何解决?

【问题讨论】:

    标签: azure .net-core dependency-injection azure-functions azure-durable-functions


    【解决方案1】:

    我想创建一个 Azure 持久函数,该函数将从 Internet 下载 CSV,并根据此文件中的数据,使用 EntityFramework 更新我的数据库。

    通过以下方式在 StartUp 中配置 DI:

    public override void Configure(IFunctionsHostBuilder builder) {
        var connectionString = Environment.GetEnvironmentVariable("DefaultConnection");
    
        builder.Services.AddDbContext<IDbContext, SqlContext>(options => 
            options.UseSqlServer(connectionString)); //To inject DbContext
    
        builder.Services.AddHttpClient(); //To inject HttpClient
    }
    

    确保您在 Azure Functions Runtime V3+ 上托管您的函数应用,因此类和方法不必是 静态

    这将允许具有可注入参数的非静态构造函数的常规类

    public class MyFunction {
        private readonly HttpClient httpClient;
        private readonly IDbContext dbContext;
    
        //ctor
        public MyFunction(IHttpClientFactory factory, IDbContext dbContext) {
            httpClient = factory.CreateClient();
            this.dbContext = dbContext;
        }
    
        [FunctionName("Function_Name_Here")]
        public async Task Run(
            [OrchestrationTrigger] IDurableOrchestrationContext context) {
    
            // ... access dependencies here
    
        }
    
        // ... other functions, which can include static, but they wont
        // have access to the instance fields.
    }
    

    本系列文章可能对你有所帮助

    A Practical Guide to Azure Durable Functions — Part 2: Dependency Injection

    【讨论】:

    • 谢谢恩科西。您的回答,尤其是“确保您在 Azure Functions Runtime V3+ 上托管您的函数应用程序,因此类和方法不必是静态的”向我保证我一定做错了其他事情。我又这样做了,在这里和那里修复了我的代码,一切都按预期工作。感谢上帝,这些函数不必是静态的 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 2018-06-28
    • 2023-01-31
    • 2020-03-04
    • 1970-01-01
    • 2019-10-15
    相关资源
    最近更新 更多