Load host IConfiguration from supplied command line args; - asp.net

ASP.NET Core apps configure and launch a host. The host is responsible for app startup and lifetime management by auto-generating a “Program.cs”, which takes care of setting up a host.
According to the documentation, if you use CreateDefaultBuilder, the following defaults are applied to HostBuilder:
load host IConfiguration from supplied command line args;
load app IConfiguration from environment variables;
Does anyone have information on how the arguments affect the CreateDefaultBuilder?
If I pass arguments on the following code, How can I access that?
static void Main(string[] args)
{
IHostBuilder common= Host.CreateDefaultBuilder(args)
}

I just found out how to use IConfiguration. If you Inject "foo:123" on the arguments, you could store it this way:
IConfiguration Configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.AddCommandLine(args)
.Build();
var customSection = Configuration.GetSection("foo");

Related

How to get value from Configuration object via HostBuilder?

Started a new Console app in .NET 6 and am adding Dependency Injection. In the code below, how can I get access to the IConfiguration object to read a value from appsettings (after calling Build?
The configuration is available within the StoreFactory service, as its injected via the constructor, but if I want to read values from appsettings within the main section of code within program.cs, how can I get at it?
program.cs
var SvcBuilder = new HostBuilder()
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(Directory.GetCurrentDirectory());
config.AddJsonFile("appsettings.json", optional: true);
config.AddEnvironmentVariables();
if (args != null)
{
config.AddCommandLine(args);
}
})
.ConfigureServices((hostContext, services) =>
{
services.AddLogging(configure => configure.AddConsole())
.AddTransient<IStoreFactory, StoreCtxFactory>();
});
var host = SvcBuilder.Build();
The Host.CreateDefaultBuilder defines the behavior to discover the JSON configuration and expose it through the IConfiguration instance. From the host instance, you can ask the service provider for the IConfiguration instance and then ask it for values.
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using IHost host = Host.CreateDefaultBuilder(args).Build();
// Ask the service provider for the configuration abstraction.
IConfiguration config = host.Services.GetRequiredService<IConfiguration>();
// Get values from the config given their key and their target type.
var configValueInt = config.GetValue<int>("yourKeyName");
string configValueStr = config.GetValue<string>("yourKeyName");
For more information read the Docs.

Read appsettings.json keys in methods other than Main Program.cs .NetCore 3.1 console app

Basically I have to call a REST API from a .netcore console app which will return me some xml and then this console app will need to create a csv file from that xml.
I need to keep the REST API url and csv path in my appsettings.config.
I have created two keys for that.
Now I don't want to read these keys in my main method but I am building ConfigurationBuilder in my main method and therefore its available only in Main method.
Code in my Main method looks like below.
configuration = new ConfigurationBuilder()
.AddJsonFile($"appsettings.json", true, true)
.AddEnvironmentVariables()
.Build();
where configuration is static IConfiguartion configuration = null at Program.cs class level.
For now I have made this ConfigurationBuilder as a class level static variable , initilaizing it in Main then reading it elsewhere but not sure if its a good approach or there's some better way of doing this?
Any suggestions would be appreciated.
In my opinion you should use Dependency Injection like described in #Marco Luzzaras comment.
But if it is not possible in you scenario you can also access the same configuration by encapsule everything in a Singleton
public class ConfigurationProvider
{
private static IConfiguration _instance;
public static IConfiguration Instance
{
get
{
if(_instance == null)
{
_instance = new ConfigurationBuilder()
.AddJsonFile($"appsettings.json", optional: true)
.AddEnvironmentVariables()
.Build();
}
return _instance;
}
}
}
... and use it everywhere you need it.
dotnet fiddle Example

Accessing Azure App Configuration from a console application

I am trying to access App configuration with a simple console app. So far I have:
static void Main(string[] args)
{
IConfiguration config = new ConfigurationBuilder()
.AddUserSecrets("e7315677-d6aa-41ab-b7cc-8e801a7c8ae9")
.AddAzureAppConfiguration("ConnectionStrings:AppConfig")
.Build();
Console.WriteLine("Hello World!");
}
But an exception is thrown indicating that
System.ArgumentException: 'Connection string doesn't have value for keyword 'ConnectionStrings:AppConfig'.'
I have put this connection string in secrets.json and I know that it is valid. What am I doing wrong?
{
"ConnectionStrings:AppConfig": "<my connection string>"
}
Thank you.
Kevin
Make sure the connection string begins with "Endpoint=". It's looking for key/value pairs, and interprets a value without a key as a key without a value.
The AddAzureAppConfiguration method expects a connection string as an argument. You receive System.ArgumentException since "ConnectionStrings:AppConfig" is not a valid connection string.
In order to use the connection string defined in the user secrets to initialize the Azure App Configuration provider, we can first build an IConfiguration instance with the user secret and use it to access the connection string property. Here's a modified version of your code that works.
static void Main(string[] args)
{
IConfiguration intermediate = new ConfigurationBuilder()
.AddUserSecrets("e7315677-d6aa-41ab-b7cc-8e801a7c8ae9")
.Build();
IConfiguration configuration = new ConfigurationBuilder()
.AddAzureAppConfiguration(intermediate["ConnectionStrings:AppConfig"])
.Build();
}
Don't make the same mistake I did and copy the endpoint from the Azure App Service portal. Look for the primary key section and there is a copy button there for the connection string. It should then give you aa string that includes that starts Endpoint= and includes the id and secret

Add new configuration provider to IConfiguration in Azure Function v2.0

I have a .NET Core Azure Function v2.0 and I'd like to inject a custom configuration provider during startup; however, it doesn't look like the IWebJobsBuilder provides a way to do additional configuration during the initialization sequence. Am I missing something or is there really not a way to inject these settings?
Yes its possible to add additional json provider. From your startup you can do like this. You can make use of the AddJsonFile method.
public void Configure(IWebJobsBuilder builder)
{
var config = new ConfigurationBuilder()
.SetBasePath(context.FunctionAppDirectory)
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddJsonFile("secret.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
}

How to set environment variables from appsettings.json for .net core console app?

I'm working with a C# class that reads from appsettings using
Environment.GetEnvironmentVariable("setting")
I want to make another console program (.net core 3.0) that reads settings from appsettings.json and loads them into environment variables.
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
IConfiguration config = builder
.Build();
var businessLogic = new BusinessLogic(); // uses GetEnvironmentVariable to get configuration
}
In my business logic class, the environment variables aren't getting pulled back correctly. What might be the problem?
appsettings.json is in this format:
{
"SETTING" : "setting value"
}
Environment.GetEnvironmentVariable("setting") will always try to read the data from an environment variable, not from your loaded config.
You need to change your BusinessLogic class to accept the config object you built and use that to access the settings. An example:
public class BusinessLogic
{
public BusinessLogic(IConfiguration config)
{
var value = config.GetValue<string>("SETTING");
}
}
In this example value will contain the correct value of SETTING if it was last set in appsettings.json or using an environment variable.

Resources