.Net 5 Azure Function App 使用 Startup class

.Net 5 Azure Function App with use of Startup class

我已经创建了一个基于 HTTP 触发器的 .Net 5 Azure FunctionApp 并尝试为我的服务配置数据库连接字符串和依赖注入 类 但是,我不知道如何调用我的配置方法来自 Program.cs 主函数的 Startup.cs 个文件。我是基于 FunctionApp 的托管新手。

我已经在 Program.cs 文件中尝试使用 IHostBuilder,但它说:“不包含 ConfigureWebHostDefaults 的定义”甚至使用了命名空间 => 使用 Microsoft.AspNetCore.Hosting;

public static void Main(string[] args)
{
    var host = new HostBuilder().ConfigureFunctionsWorkerDefaults()            
            .Build();

    //CreateHostBuilder(args).Build().Run();
    host.Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
   webBuilder.UseStartup<Startup>();
});

我的 Startup.cs 文件,

[assembly: FunctionsStartup(typeof(Startup))]
namespace kpi
{
  public class Startup : FunctionsStartup
  {
    private static IConfiguration _configuration = null;        

    public override void Configure(IFunctionsHostBuilder builder)
    {
        var serviceProvider = builder.Services.BuildServiceProvider();
        _configuration = serviceProvider.GetRequiredService<IConfiguration>();
        var appSettingsSection = _configuration.GetSection("AppSetting");
        builder.Services.Configure<AppSetting>(appSettingsSection);
        var appSettings = appSettingsSection.Get<AppSetting>();
        RuntimeConfig.appsettings = appSettings;

        var ConnectionString = RuntimeConfig.appsettings.AppDBConnection;
        builder.Services.AddDbContext<ShardingDbContext>(options => 
       options.UseSqlServer(ConnectionString), ServiceLifetime.Transient);
    }
  }
}

我使用了 FunctionStartup 程序集,我不知道哪里出错了,谁能帮我从 Startup.cs 文件配置我的连接字符串?

Azure 函数有两种风格,两者的依赖注入配置不同。 From the doc:

Previously Azure Functions has only supported a tightly integrated mode for .NET functions, which run as a class library in the same process as the host. This mode provides deep integration between the host process and the functions. For example, .NET class library functions can share binding APIs and types. However, this integration also requires a tighter coupling between the host process and the .NET function. For example, .NET functions running in-process are required to run on the same version of .NET as the Functions runtime. To enable you to run outside these constraints, you can now choose to run in an isolated process. This process isolation also lets you develop functions that use current .NET releases (such as .NET 5.0), not natively supported by the Functions runtime.

两种模式之间有 a bunch of differences,因此请务必检查它们以选择符合您要求的模式。

进程内 Azure 函数

使用此配置,您的 Azure 函数与主机 运行时间紧密耦合。在撰写本文时,这意味着您的 Azure 函数无法在 .NET5 上 运行。

您将需要以下 NuGet 包:

  • Microsoft.Azure.Functions.Extensions
  • Microsoft.NET.Sdk.Functions 版本 1.0.28 或更高版本
  • Microsoft.Extensions.DependencyInjection

FunctionsStartup 属性与 Startup class:

一起使用
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;

[assembly: FunctionsStartup(typeof(MyNamespace.Startup))]
namespace MyNamespace
{
  public class Startup : FunctionsStartup
  {
    public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
    {
        var context = builder.GetContext();

        // optional: customize your configuration sources 
        // here, we add appsettings.json files 
        // Note that these files are not automatically copied on build or publish. 
        builder.ConfigurationBuilder
            .AddJsonFile(Path.Combine(context.ApplicationRootPath, "appsettings.json"), optional: true, reloadOnChange: false)
            .AddJsonFile(Path.Combine(context.ApplicationRootPath, $"appsettings.{context.EnvironmentName}.json"), optional: true, reloadOnChange: false);
    }
    
    public override void Configure(IFunctionsHostBuilder builder)
    {
        // get the configuration from the builder
        var configuration = builder.GetContext().Configuration;
    }
}

在此处查看更多信息:https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection

隔离进程 Azure 函数

在此模式下,您的 Azure 函数与主机 运行time 完全分离(这与允许使用 C# 以外的语言编写 Azure 函数的模式相同)。您负责创建主机。

您将需要以下 NuGet 包:

  • Microsoft.Azure.Functions.Worker
  • Microsoft.Azure.Functions.Worker.Sdk
  • Microsoft.Azure.Functions.Worker.Extensions

这里没有Startupclass;您负责在 Program.cs:

中自己创建主机
using Microsoft.Extensions.Hosting;

public static async Task Main(string[] args)
{  
  var builder = Host
    .CreateDefaultBuilder(args)
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureAppConfiguration((hostingContext, configBuilder) =>
    {
        // optional: customize your configuration sources 
        // here, we add appsettings.json files 
        // Note that these files are not automatically copied on build or publish. 
        var env = hostingContext.HostingEnvironment;
        configBuilder
          .AddJsonFile($"appsettings.json", optional: true, reloadOnChange: true)
          .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
          ;
    })
    .ConfigureServices((appBuilder, services) =>
    {
        var configuration = appBuilder.Configuration;
    });

    await builder.Build().RunAsync();
}

在此处查看更多信息:https://docs.microsoft.com/en-us/azure/azure-functions/dotnet-isolated-process-guide

复制appsettings.json文件到输出目录

默认情况下,Azure 函数无法识别 appsettings.json 个文件。您需要通过ConfigureAppConfiguration将它们添加到应用程序配置中,但您还需要将它们复制到输出目录,否则函数应用程序将无法找到它们。

为此,请将以下行添加到您的 .csproj:

<ItemGroup>
  <None Include="appsettings.json">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </None>
  
  <None Include="appsettings.*.json"> 
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    <DependentUpon>appsettings.json</DependentUpon>
  </None>
</ItemGroup>