Environment for generic host integration
See original GitHub issueWhen using the generic host integration, I would like the command line parser to be able to set the the host’s environment (IHostEnvironment.EnvironmentName
). This can be done statically like this:
static Task<int> Main(string[] args)
=> new HostBuilder()
.UseEnvironment("Development")
.RunCommandLineApplicationAsync<Program>(args);
The default builder is already configured to take this from the --environment
command line option. So you can run normal applications using foo.exe --environment Development
to set the environment. I would like to keep this option working in order to switch the active application configuration, just like the default host builder does by default.
Right now, I’m doing this to allow setting the environment:
.ConfigureHostConfiguration(config =>
{
var configApp = new CommandLineApplication();
configApp.UnrecognizedArgumentHandling = UnrecognizedArgumentHandling.CollectAndContinue;
var envOption = configApp.Option("--environment", null, CommandOptionType.SingleValue);
configApp.Execute(args);
var environment = envOption.Value();
if (!string.IsNullOrEmpty(environment))
{
config.AddInMemoryCollection(new Dictionary<string, string>
{
[HostDefaults.EnvironmentKey] = environment,
});
}
})
In addition, I also configure the same --environment
parameter for the actual program to avoid that throwing later.
Ideally, I would like the RunCommandLineApplicationAsync
take care of this automatically. Since it operates on the host builder, it could configure a host configurator as well. There just would be some need to maybe extract the argument parsing so that this doesn’t need to instantiate a full temporary app here the way I do.
Issue Analytics
- State:
- Created 3 years ago
- Comments:10 (2 by maintainers)
Yes and no. It’s not really supported. In an ideal world where I have loads of free time, I would have liked to split the parsing code from the code that contains the application lifecycle. In the real world, I’ve never found the time.
That said, you might be able to get this partially working with workarounds. You should be able to re-use instances of
CommandLineApplication
. If you call the.Parse
method multiple times without it calling any “OnExecute” handlers. The think I think might trip it up (not sure, whould need to test) is usages ofCommandLineApplication<TModel>
. Parsing may initialize theTModel
…which might defeat the whole purpose of theParse
only method…but I attempted to make this initialization as lazy as possible in #332.I’m not sure. The hosting integration was almost entirely built by others. I have reviewed the code to make sure it wasn’t obviously flawed and made of a few minor fixes, but otherwise, I haven’t spent much time on it myself.
Closing due to inactivity. If you are looking at this issue in the future and think it should be reopened, please make a commented here and mention natemcmaster so he sees the notification.