Home > Software design >  .Net 6 Azure Function App with use of Startup class
.Net 6 Azure Function App with use of Startup class

Time:05-25

I have created an HTTP trigger-based .Net 6 Azure FunctionApp and trying to configure the database connection strings, other key values, and dependency injections for my service classes but, I don't know how to call my configure method of Startup.cs file from Program.cs main function. I am new to FunctionApp-based hosting.

I have tried with IHostBuilder like the following in the Program.cs file, but it says: "does not contain a definition for ConfigureWebHostDefaults" even used the namespace => using 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>();
 });

My Startup.cs file,

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

I have used the FunctionStartup assembly, I don't know where I did go wrong, Can anyone help me to configure my connection strings from Startup.cs file in .Net6 Function App project?

CodePudding user response:

You can refer below code to fix your issue. For more details, please read official doc.

Guide for running C# Azure Functions in an isolated process

1. Startup.cs file

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 file

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

CodePudding user response:

I just did override the function ConfigureAppConfiguration as below

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

It's working fine in my local without an isolated way or Program.cs file and I don't know whether this same code will work on a server or not.

My local.setings.json

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

My Startup.cs file below and I can access the AppSettings section from my json file

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();
    }
}
  • Related