Search code examples
dependency-injectionazure-functionsconnection-string.net-7.0

Can't get my connection string in .Net7.0 Azure function app program.cs file


I've looked at a couple of examples (Azure Function, .Net7) of how to get my connection string to set my db context in startup.cs, but I can't seem to figure out how to get my connection string.

From multiple examples I've seen online, they say use:

var sqlConnectionString = Configuration.GetConnectionString("SqlServerConnection");

but I can't seem to find the right library to use it! "System.Configuration" is what VS Code suggests I import but when I click on it to use, I see an eror under "GetConnectionString" that says it can't be found for "Configuration". So that doesn't seem to be correct.

Some online tutorials says to use "Microsoft.Extensions.Configuration", but not sure if that it accurate as I can't seem to associate the lib/package with the code to use it and I tried installing the nuget package manually here. Not sure if this is needed?

<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />

Here is my program.cs file where I'm trying to read in my connection string.

using Core.Helpers;
using Core.Interfaces;
using Infrastructure.Data;
using Infrastructure.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.Azure.Functions.Worker;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Functions
{
    public class Program
    {
        static async Task Main(string[] args) {

            // can't find Configuration
            var sqlConnectionString = Configuration.GetConnectionString("SqlServerConnection");
            
            var host = new HostBuilder()
                .ConfigureFunctionsWorkerDefaults(builder =>
                {
                    builder
                    .AddApplicationInsights()
                    .AddApplicationInsightsLogger();

                    builder.Services.AddOptions<SendGridOptions>()
                        .Configure<IConfiguration>((settings, configuration) =>
                        {
                            configuration.GetSection("SendGrid").Bind(settings);
                        });
                    builder.Services.AddScoped<IEmailService, EmailService>();
                    builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();
                    builder.Services.AddScoped<IServiceBusProducer, ServiceBusProducer>();
                })
                .ConfigureServices(s =>
                {
                    s.AddDbContext<DataContext>(options => {
                        options.UseSqlServer(sqlConnectionString, y => y.UseNetTopologySuite());
                    });
                })
                .Build();

            await host.RunAsync();
            
        }
    }
}


Solution

  • I have tried to reproduce the same in my environment and I could get the connection string in startup class.

    • Created a .net7 Azure function application.
    • Used below code to get the connection string in program.cs

    Code Snippet:

    public class Program
        {        
    
            public static void Main(string[] args)
            {
                CreateHostBuilder(args).Build().Run();
            }
    
            public static IHostBuilder CreateHostBuilder(string[] args) =>
                Host.CreateDefaultBuilder(args)
                    .ConfigureAppConfiguration((hostingContext, config) =>
                    {
                        config.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true);
                        config.AddEnvironmentVariables();
                    })
                    .ConfigureServices((hostContext, services) =>
                    {
                        IConfiguration configuration = hostContext.Configuration;
    
                        string connectionString = configuration.GetConnectionString("AppConfig");
                        Console.WriteLine("DB connection string:" +connectionString);
                        // configure your database context            
        }
    

    local.settings.json:

    {
      "IsEncrypted": false,
      "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated"
      },
      "ConnectionStrings": {
        "AppConfig": "Server=tcp:servername.database.windows.net,1433;Database=pravudb;User Id=your_username;Password=your_password;"
      }
    }
    

    Dependencies:

     <ItemGroup>
        <PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.1.0" />
        <PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.14.1" />
        <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.0.13" />
        <PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.10.0" />
        <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" />
        <PackageReference Include="Microsoft.Extensions.Configuration.AzureAppConfiguration" Version="6.0.1" />
      </ItemGroup>
    

    Response: enter image description here

    enter image description here