Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net 5 Azure Function App with use of Startup class

I have created an HTTP trigger-based .Net 5 Azure FunctionApp and trying to configure the database connection strings 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();

    //CreateHostBuilder(args).Build().Run();
    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?

like image 342
Md Aslam Avatar asked Jan 20 '26 16:01

Md Aslam


1 Answers

There are two flavors of Azure functions, and the configuration of the dependency injection is different between the two. 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.

There are a bunch of differences between the two modes, so be sure to check them to chose the one that matches your requirements.

In-process Azure function

With this configuration, your Azure function is tightly coupled with the host runtime. At the time of writing, that means your Azure function can't run on .NET5.

You'll need the following NuGet packages:

  • Microsoft.Azure.Functions.Extensions
  • Microsoft.NET.Sdk.Functions version 1.0.28 or later
  • Microsoft.Extensions.DependencyInjection

The FunctionsStartup attribute is used with a 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;
    }
}

See more information here: https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection

Isolated process Azure function

In this mode, your Azure function is completely decoupled from the host runtime (this is the same mode that allows Azure functions to be written in languages other than C#). You're responsible from creating the Host.

You'll need the following NuGet packages:

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

There's no Startup class here; you're responsible for creating the Host yourself in 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();
}

See more information here: https://learn.microsoft.com/en-us/azure/azure-functions/dotnet-isolated-process-guide

Copy the appsettings.json file to the output directory

By default, Azure functions are not aware of appsettings.json files. You need to them to the app configuration via ConfigureAppConfiguration, but you also need to copy them to the output directory, otherwise the function app won't be able to find them.

To do that, add the following lines to your .csproj:

<ItemGroup>
  <None Include="appsettings.json">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </None>
  
  <None Include="appsettings.*.json"> 
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    <DependentUpon>appsettings.json</DependentUpon>
  </None>
</ItemGroup>
like image 179
Métoule Avatar answered Jan 23 '26 04:01

Métoule



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!