.Net 6 Azure Function App 使用 Startup class

.Net 6 Azure Function App with use of Startup class

我已经创建了一个基于 HTTP 触发器的 .Net 6 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();


 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 程序集,我不知道哪里出错了,谁能帮我从 .Net6 Function App 项目中的 Startup.cs 文件配置我的连接字符串?

您可以参考以下代码来解决您的问题。更多细节请阅读官方文档

Guide for running C# Azure Functions in an isolated process

1. Startup.cs 文件

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

[assembly: FunctionsStartup(typeof(triggerFunc.Startup))]
namespace triggerFunc
{
    public class Startup : FunctionsStartup
    {
        private static IConfiguration _configuration = null;
        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;

            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);
        }
    }
}

2。 Program.cs 文件

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace triggerFunc
{
    public class Program
    {
        public static async Task Main(string[] args)
        {
            var builder = Host
              .CreateDefaultBuilder(args)
              .ConfigureFunctionsWorkerDefaults()
              .ConfigureAppConfiguration((hostingContext, configBuilder) =>
              {
                   var env = hostingContext.HostingEnvironment;
                    ;
              })
              .ConfigureServices((appBuilder, services) =>
              {
                  var configuration = appBuilder.Configuration;
              });

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

我刚刚重写了 ConfigureAppConfiguration 函数,如下所示

public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
{
        FunctionsHostBuilderContext context = builder.GetContext();

        builder.ConfigurationBuilder
            .AddJsonFile(Path.Combine(context.ApplicationRootPath, "local.settings.json"), optional: true, reloadOnChange: false)
            .AddJsonFile(Path.Combine(context.ApplicationRootPath, $"local.settings.{context.EnvironmentName}.json"), optional: true, reloadOnChange: false)
            .AddEnvironmentVariables();
}

无需隔离方式或 Program.cs 文件,它在我的本地工作正常,我不知道同样的代码是否可以在服务器上工作。

我的local.setings.json

{
 "IsEncrypted": false,
 "AppSettings": {
 "AppDBConnection": "xyz....."
}

我的 Startup.cs 文件如下,我可以从我的 json 文件

访问 AppSettings 部分
public class Startup : FunctionsStartup
{

    private static IConfiguration _configuration = null;
    
    public override void Configure(IFunctionsHostBuilder builder)
    {
        //var connectionString = Environment.GetEnvironmentVariable("ConnectionStrings:DBConnection");

        var serviceProvider = builder.Services.BuildServiceProvider();
        _configuration = serviceProvider.GetRequiredService<IConfiguration>();
        var appSettingsSection = _configuration.GetSection("AppSettings");
        builder.Services.Configure<AppSettings>(appSettingsSection);
        var appSettings = appSettingsSection.Get<AppSettings>();
        RuntimeConfig.appsettings = appSettings;

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

    public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
    {
        FunctionsHostBuilderContext context = builder.GetContext();

        builder.ConfigurationBuilder
            .AddJsonFile(Path.Combine(context.ApplicationRootPath, "local.settings.json"), optional: true, reloadOnChange: false)
            .AddJsonFile(Path.Combine(context.ApplicationRootPath, $"local.settings.{context.EnvironmentName}.json"), optional: true, reloadOnChange: false)
            .AddEnvironmentVariables();
    }
}