新的 Azure Function 3.0 SDK 提供了一种实现 Startup 类的方法。它允许访问依赖注入可用的服务集合,我可以在其中添加自己的组件和第三方服务。
但我不知道如何使用配置文件。
[assembly: FunctionsStartup(typeof(MyNamespace.Startup))]
namespace MyNamespace
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
...
Run Code Online (Sandbox Code Playgroud)
我的第三方服务以大型结构为参数,这些配置文件与二进制文件一起复制。我可以将它们复制到appsettings.json文件的一个小节中:
{
"MachineLearningConfig" : {
( about 50+ parameters and subsections )
}
}
Run Code Online (Sandbox Code Playgroud)
根据部署环境更新配置值。为此,我使用 Azure Devops 的文件转换任务:生产值不同于 staging 和 dev 值。
鉴于文档https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection加载这些选项的方法是:
builder.Services.AddOptions<MachineLearningConfig>()
.Configure<IConfiguration>((settings, configuration) =>
{
configuration.GetSection("MachineLearningConfig").Bind(settings);
});
Run Code Online (Sandbox Code Playgroud)
但这需要将所有设置添加为主机环境中的键/值字符串,这是我不想做的。它们太多了,不像在 json 配置文件中那样容易维护。
我将appsettings.json与host.json一起复制。
但是Azure Function SDK 在启动时读取的appsettings.json文件不是我的应用程序的 appsettings.json,而是 Azure Function …
我在 .NET core 3.1 中有一个 Azure 函数 v3,函数在本地运行良好。这是 local.settings.json:
{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"AzureWebJobsStorage": "UseDevelopmentStorage=true"
},
"Foo": {
"Bar": {
"test1": true,
"test2": false
}
}
}
Run Code Online (Sandbox Code Playgroud)
我需要在 Azure 函数配置中为 Foo:Bar:test1 等嵌套对象编写配置。
如何在那里表达这个嵌套对象?
如何获取对函数启动类中的ExecutionContext.FunctionAppDirectory的访问权限,以便我可以正确设置我的Configuration。请查看以下启动代码:
[assembly: WebJobsStartup(typeof(FuncStartup))]
namespace Function.Test
{
public class FuncStartup : IWebJobsStartup
{
public void Configure(IWebJobsBuilder builder)
{
var config = new ConfigurationBuilder()
.SetBasePath(“”/* How to get the Context here. I cann’t DI it
as it requires default constructor*/)
.AddJsonFile(“local.settings.json”, true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
}
}
}
Run Code Online (Sandbox Code Playgroud) azure azure-functions azure-functions-runtime azure-functions-core-tools
我有一个 Azure 函数,我正在使用 DI 系统来注册一些类型;例如:
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services
.AddTransient<IMyInterface, MyClass>()
. . . etc
Run Code Online (Sandbox Code Playgroud)
但是,我还要从我的环境设置中注册一些数据。在函数本身内部,我可以获得ExecutionContext
, 所以我可以这样做:
IConfiguration config = new ConfigurationBuilder()
.SetBasePath(context.FunctionAppDirectory)
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
Run Code Online (Sandbox Code Playgroud)
但是,在 FunctionsStartup 中,我无权访问ExecutionContext
. 有没有一种方法可以从 FunctionsStartup 类中获取 ExecutionContext ,或者另一种确定当前运行目录的方法,以便我可以设置基本路径?