.NET Core Web Project - Using Command Line Arguments

I want to pass a DbConnectionString through a command line argument to a .NET Core Web API application.

After reading:

Command line .NET core Pass Command Args for Startup.cs from Program.cs

My Program.cs looks something like this:

        public static void Main(string[] args) {

        var config = new ConfigurationBuilder()
            .AddCommandLine(args)
            .Build();
        var host = new WebHostBuilder() 
            .UseKestrel()
            .UseConfiguration(config)
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .Build();

        host.Run();
    }

So now ... I added the args command line to the configuration collection of the key value pair of my WebHostBuider ...

However, in Startup.cs there is where I register everything, for example, DbContext (which requires that DbConnectionString be passed as a command line argument)

The constructor for My Startup is as follows:

        public Startup(IHostingEnvironment env) {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

Since earlier my connection string was stored in the configuration file.

: Startup.cs?? IConfiguration IConfigurationRoot Startup.cs, .

+4
1

.ConfigureServices(s => s.AddSingleton<IConfigurationRoot>(config))

.cs. ​​:

public static void Main(string[] args) {
        var config = new ConfigurationBuilder()
            .AddCommandLine(args)
            .Build();
        var host = new WebHostBuilder() 
            .UseKestrel()
            .UseConfiguration(config)
            .ConfigureServices(s => s.AddSingleton<IConfigurationRoot>(config))
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .Build();

        host.Run();
    }`
0

Source: https://habr.com/ru/post/1680371/


All Articles