gpt4 book ai didi

azure - 如何在 Azure Durable Functions 中使用依赖注入(inject)?

转载 作者:行者123 更新时间:2023-12-02 18:50:32 24 4
gpt4 key购买 nike

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

我设置了使用 TimeTrigger 触发的简单启动功能。该函数负责启动协调器。协调器并行执行多个事件。大约有 40000 个工作项需要处理,这就是 Orchestrator 触发的事件数量。其中一些事件需要更新数据库(插入/更新/删除行)。为此,我需要一个数据库连接。我可以通过以下方式在 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函数,以便它可以在需要时更新数据库中的数据。

我该如何解决?

最佳答案

I want to create an Azure Durable Function that will download a CSV from the Internet and based on the data in this file, it will update my database using 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+ 上,以便类和方法不必是静态

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

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 - 如何在 Azure Durable Functions 中使用依赖注入(inject)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66852560/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com