本文介绍了.NET Core Web项目-使用命令行参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过命令行参数将DbConnectionString传递给我的.NET Core Web API应用.

I want to pass in the DbConnectionString via command line argument to my .NET Core Web API app.

阅读后:

.NET core将命令行Args传递给来自Program.cs的Startup.cs

我的Program.cs类似于:

My Program.cs looks something like:

        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();
    }

所以现在...我已将命令行args添加到WebHostBuider的键值对配置的集合中.

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

但是,在Startup.cs中,我注册了所有内容,例如我的DbContext(这需要将DbConnectionString作为命令行arg传递)

However, In Startup.cs is where I register everything such as my DbContext (which requires the DbConnectionString passed as a command line arg)

我的Startup构造函数如下:

My Startup constructor looks like this:

        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();
    }

由于之前,我的连接字符串已存储在Config文件中.

Because previously, my connection string was being stored in a Config file.

我的问题是-如何从Startup.cs中访问命令行参数?我已经在Startup.cs中尝试使用IConfiguration和IConfigurationRoot进行构造函数注入,但是都未注册​​.

My Question is - How do I access the Command Line args from within Startup.cs ??I have tried constructor injection with IConfiguration and IConfigurationRoot in Startup.cs but neither of these are registered.

推荐答案

我不见了

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

在我的program.cs中.固定版本如下:

In my program.cs. Fixed version as follows:

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();
    }`

这篇关于.NET Core Web项目-使用命令行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 05:45