azure - 在本地运行 Azure Functions 时使用 stub

标签 azure dependency-injection azure-functions

我有一个 Azure Functions (.NET Core) 项目,我想根据环境为某些类选择实现。类似于以下内容:

public class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        builder.Services.AddLogging();
        #if azure environment
        builder.Services.AddSingleton<IAzureApi, AzureApi>();
        #else
        builder.Services.AddSingleton<IAzureApi, AzureApiStub>();
        #endif
    }
}

最好的方法是什么?是否可以在 local.settings.json 中配置这种行为?

最佳答案

通过在配置文件中使用自定义属性来实现此目的的简单方法。

 [FunctionName("CustomSettings")]
public static Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "GET")]HttpRequestMessage req, TraceWriter log)
{
    var customSetting =  Environment.GetEnvironmentVariable("AzureEnvironment", EnvironmentVariableTarget.Process);
    if(customSetting == "Development")
    {
        //dosomething
    }
}

在 Azure 门户中手动添加此属性 (AppSettings)。
了解更多信息 -> https://learn.microsoft.com/en-us/sandbox/functions-recipes/environment-variables?tabs=csharp
https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-class-library#environment-variables

关于azure - 在本地运行 Azure Functions 时使用 stub ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61477112/

相关文章:

Azure 事件目录配置

c# - 如何将 ApplicationDbContext 传递给 ASP.NET MVC5 构造函数?

c# - 在 AzureFunction 上使用 RSACryptoServiceProvider

azure - 删除并重新创建发布配置文件 VS 2017 后旧的 Azure 函数返回

azure - 如何从 vs code 发布 azure 函数?

c# - 从 asp.net core 身份验证 Web 应用程序获取 Microsoft Graph 的访问 token

azure - 如何从Azure数据工厂中的上一行获取数据

c# - Azure Function 引用混合模式程序集

java - 如何让 PicoContainer 启动/停止/处置工厂注入(inject)的组件?

javascript - Typescript 中的闭包(依赖注入(inject))