Oleg Sh
Oleg Sh

Reputation: 9013

Azure Function v2 and connection strings

I have the following local.settings.json file:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "AzureWebJobsDashboard": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",

    "SureMdmApiKey": "xxx",
    "SureMdmApiUrl": "xxx",
    "SureMdmUsername": "xxx",
    "SureMdmPassword": "xxx"
  },
  "ConnectionStrings": {
    "StorageConnectionString": "aaaa",
    "DataContext": "aaaa"
  }
}

then I have the following code in Startup.cs file:

[assembly: FunctionsStartup(typeof(FunctionAppSureMdmSync.Startup))]
namespace FunctionAppSureMdmSync
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var services = builder.Services;

            services.AddTransient<ISureMdmService>(s => new SureMdmService(
                url: System.Environment.GetEnvironmentVariable("SureMdmApiUrl"),
                username: System.Environment.GetEnvironmentVariable("SureMdmUserName"),
                password: System.Environment.GetEnvironmentVariable("SureMdmPassword"),
                apiKey: System.Environment.GetEnvironmentVariable("SureMdmApiKey")
                ));

            var connString = System.Environment.GetEnvironmentVariable("ConnectionStrings:DataContext");
            services.AddDbContext<DataContext>(options => options
                .UseSqlServer(connString, x => x.UseNetTopologySuite()));


            services.AddTransient<ITabletGroupService, TabletGroupService>();
            services.AddTransient<ITabletService, TabletService>();
        }

    }
}

and it works fine on local

But when I publish this function to Azure Portal and go to "Configuration" and add "DataContext" to "Connection Strings":

enter image description here

My code does not work:

            var connString = System.Environment.GetEnvironmentVariable("ConnectionStrings:DataContext");

How to get connection string? I want that it works both, on local and Portal Azure?

Upvotes: 2

Views: 2557

Answers (3)

Carlos Alves Jorge
Carlos Alves Jorge

Reputation: 1985

The way I do to connect to a SQL server on my azure functions is like this:

var config = new ConfigurationBuilder()
           .SetBasePath(context.FunctionAppDirectory)
           .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
           .AddEnvironmentVariables()
           .Build();

var str = config.GetConnectionString("DataContext");

In the function parameters:

public static void Run( blablabla,
            ExecutionContext context
            )

Upvotes: 0

sellotape
sellotape

Reputation: 8325

I’ve found that to access IConfiguration in Startup, you need to build a temporary service provider, that you just throw away. There might be better ways more recently, but it still works fine:

var configuration = builder.Services.BuildServiceProvider().GetService<IConfiguration>(); 

Then, don’t use System.Environment.GetEnvironmentVariable(), but IConfiguration instead (same applies for all your configuration):

var connString = configuration.GetConnectionString("DataContext");

Upvotes: 8

Raffy
Raffy

Reputation: 605

You need to add the variable in the Configuration as ConnectionStrings:DataContext.

Upvotes: 0

Related Questions