簡體   English   中英

如何在 Azure Function V3 中使用 IOptions 模式,使用 .NET 核心

[英]How to use IOptions pattern in Azure Function V3 using .NET Core

我的要求是使用 IOptions 模式從 local.settings.json 讀取值

我的 localsettings.json:

{
  "IsEncrypted": false,
  "Values": {
    "MyOptions:MyCustomSetting": "Foobar",
    "MyOptions:DatabaseName": "Confirmed",
    "MyOptions:Schema": "User",
    "MyOptions:Role": "Dev",
    "MyOptions:UserName": "Avinash"
  }
}

我的綁定 class 看起來像:

public class MyOptions
    {
        public string MyCustomSetting { get; set; }
        public string DatabaseName { get; set; }
        public string Schema { get; set; }
        public string Role { get; set; }
        public string UserName { get; set; }
    }

啟動.cs

[assembly: FunctionsStartup(typeof(FunctionApp2.Startup))]
namespace FunctionApp2
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddSingleton<IEmployee, Employee>();

            builder.Services.AddOptions<MyOptions>()
                .Configure<IConfiguration>((settings, configuration) =>
                {
                    configuration.GetSection("MyOptions").Bind(settings);
                });
        }
    }

我的消費 class:

    public class Employee: IEmployee
    {
        private readonly MyOptions _settings;

        public Employee(IOptions<MyOptions> options)
        {
            _settings = options.Value;
        }
    }

當且僅當我在 local.settings.json 中使用MyOptions:編寫屬性前綴時,它才能正常工作,因此我能夠從 Employee class 讀取值。

但我想在 local.settings.json 中保留我的詳細信息:

{
  "MyOptions":{
    "MyCustomSetting": "Foobar",
    "DatabaseName": "Confirmed",
    "Schema": "User",
    "Role": "Dev",
    "UserName": "Manish"
   }
}

如果我像上面那樣維護我的設置文件,那么我將無法讀取我的員工 class 中的值。

有人可以幫我解決這個問題嗎?

那么實際上你不能也不應該。 Local.settings.json 不是您在配置中加載的經典 json 配置文件。 It's a file containing settings that will be loaded by the azure function runtime as environment variables to mimic what happen on Azure with the Azure application settings. 它與 ASP.NET 核心 Web 應用程序中的 appsetttings.json 不同。 在 local.settings.json 中,設置的格式與您在 Azure 門戶中聲明的環境變量或設置相同。

據我所知,您無法以您想要的格式維護您的 local.settings.json 文件。 當然,您可以擁有另一個 json 文件,例如“appsettings.json”,並將其加載到配置中,但如果我是您,我不會這樣做,因為您將無法將所有設置放在那里(設置存在於例如,綁定不能放在那里)。

我認為一旦您習慣了:的格式,並且它將 map 配置為 json 部分,那么使用 local.settings.json 文件就可以了。

您可以使用以下格式的 local.settings.json 以使您的代碼正常工作

 { "IsEncrypted": false, "Values": { "AzureWebJobsStorage": "UseDevelopmentStorage=true", "FUNCTIONS_WORKER_RUNTIME": "dotnet" }, "MyOptions"{ "MyCustomSetting": "Foobar", "DatabaseName": "Confirmed", "Schema": "User", "Role": "Dev", "UserName": "Manish" } }

當您在 azure 門戶設置中添加這些內容時,您需要為它們添加前綴 - "MyOptions:MyCustomSetting": "Foobar"

我已經在最新的 func 應用程序版本中實現了它。 如果您遇到任何問題,請回復我

作為最佳實踐,我可以建議包裝所有相關的應用程序設置代碼,例如:

{
    "ConnectionStrings": {
    },
    "AppSettings": {
        "MyOptions": {
            ...
        }
    },
}

public class AppSettingsConfig 
{
    public MyOptions MyOptions { get; set;}
}

注冊AppSettings后,您可以通過其名稱獲取子部分,然后將其簡單地綁定到您的 class MyOptions

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
    this._appSettingsconfigurationSection = Configuration.GetSection("AppSettings");
    services.Configure<AppSettingsConfig>(this._appSettingsconfigurationSection);

    IConfigurationSection myOptionsSection = this._appSettingsconfigurationSection.GetSection("MyOptions");
    MyOptions myOptions = new MyOptions();
    myOptionsSection.Bind(myOptions);
}

我在我的 azure function.csproj 中錯過了與 local.settings.json 相關的設置

如果您使用應用服務計划,您可以使用新的appsettings.json文件並使用配置生成器注入它。

如果您使用的是消費計划或高級計划,它會間歇性地拋出錯誤,因為當應用程序開始擴展時,配置文件在啟動時不可用。

使用 json 文件的一種方法是在 function 級別進行。 您可以使用 static 方法構建一個 static class 方法,該方法可以在所有類中重用。

private static IConfigurationRoot GetConfig(ExecutionContext context)
        {
            return new ConfigurationBuilder()
                        .SetBasePath(context.FunctionAppDirectory)
                        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                        .AddEnvironmentVariables()
                        .Build();
        }

在你的觸發器中調用它


        [FunctionName("myhttptrigger")]
        public async Task<IActionResult> MyHttpTrigger(
            [HttpTrigger(AuthorizationLevel.Function, "get")] HttpRequest req, ExecutionContext context){
   var config = getConfig(context);
   // use you 


}

您甚至可以構建更高級的方法來獲取類型化配置 class 並在您的函數中調用它


public static MyOptions GetMyOptions(ExecutionContext executionContext){
    var config = GetConfig(executionContext);
    return config.GetSection("MyOptions").GetValue<MyOptions>();

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM