Reputation: 1764
I have an Azure Functions (.NET Core) project and I would like to select an implementation for some class depending on the environment. Something like the following:
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddLogging();
#if azure environment
builder.Services.AddSingleton<IAzureApi, AzureApi>();
#else
builder.Services.AddSingleton<IAzureApi, AzureApiStub>();
#endif
}
}
What would be the best way to do this? Is it possible to configure such behavior local.settings.json?
Upvotes: 0
Views: 193
Reputation: 3293
You could use the DEBUG
preprocessor directive in your Startup.cs
file:
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
#if DEBUG
builder.Services.AddSingleton<IAzureApi, AzureApiStub>();
#else
builder.Services.AddSingleton<IAzureApi, AzureApi>();
#endif
}
}
You have to be running your solution in Debug
configuration which I assume you would be doing when running locally?
Upvotes: 1
Reputation: 1182
Easy way to achieve this by using custom property in the config file.
[FunctionName("CustomSettings")]
public static Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "GET")]HttpRequestMessage req, TraceWriter log)
{
var customSetting = Environment.GetEnvironmentVariable("AzureEnvironment", EnvironmentVariableTarget.Process);
if(customSetting == "Development")
{
//dosomething
}
}
Add this property in the azure portal manually (AppSettings).
for more info -> https://learn.microsoft.com/en-us/sandbox/functions-recipes/environment-variables?tabs=csharp
https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-class-library#environment-variables
Upvotes: 1