. NET 核心控制台应用的 ASP.NET 核心配置

NET Core 支持一个新的配置系统,如下所示: Https://docs.asp.net/en/latest/fundamentals/configuration.html

.NETCore 控制台应用程序也支持此模型吗?

如果没有什么是替代以前的 app.configConfigurationManager模式?

164806 次浏览

我错了,你可以使用 netcore 控制台应用的新 ABc0。

有关示例,请参见 https://docs.asp.net/en/latest/fundamentals/configuration.html

然而,只有 aspnet 核心依赖注入是开箱即用的,所以你没有能力使用强类型配置设置并使用 IOptions自动注入它们。

您可以使用这个代码片段。它包括 Configuration 和 DI。

public class Program
{
public static ILoggerFactory LoggerFactory;
public static IConfigurationRoot Configuration;


public static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;


string environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");


if (String.IsNullOrWhiteSpace(environment))
throw new ArgumentNullException("Environment not found in ASPNETCORE_ENVIRONMENT");


Console.WriteLine("Environment: {0}", environment);


var services = new ServiceCollection();


// Set up configuration sources.
var builder = new ConfigurationBuilder()
.SetBasePath(Path.Combine(AppContext.BaseDirectory))
.AddJsonFile("appsettings.json", optional: true);
if (environment == "Development")
{


builder
.AddJsonFile(
Path.Combine(AppContext.BaseDirectory, string.Format("..{0}..{0}..{0}", Path.DirectorySeparatorChar), $"appsettings.{environment}.json"),
optional: true
);
}
else
{
builder
.AddJsonFile($"appsettings.{environment}.json", optional: false);
}


Configuration = builder.Build();


LoggerFactory = new LoggerFactory()
.AddConsole(Configuration.GetSection("Logging"))
.AddDebug();


services
.AddEntityFrameworkNpgsql()
.AddDbContext<FmDataContext>(o => o.UseNpgsql(connectionString), ServiceLifetime.Transient);


services.AddTransient<IPackageFileService, PackageFileServiceImpl>();


var serviceProvider = services.BuildServiceProvider();


var packageFileService = serviceProvider.GetRequiredService<IPackageFileService>();


............
}
}

哦,别忘了加上项目.json

{
"version": "1.0.0-*",
"buildOptions": {
"emitEntryPoint": true,
"copyToOutput": {
"includeFiles": [
"appsettings.json",
"appsettings.Integration.json",
"appsettings.Production.json",
"appsettings.Staging.json"
]
}
},


"publishOptions": {
"copyToOutput": [
"appsettings.json",
"appsettings.Integration.json",
"appsettings.Production.json",
"appsettings.Staging.json"
]
},
...
}

对于.NET Core 2.0控制台应用程序,我做了以下工作:

  1. 在项目的根目录下创建一个名为 Appsettings.json的新文件(文件名可以是任何名称)
  2. 将我的特定设置作为 json 添加到该文件中。例如:
{
"myKey1" :  "my test value 1",
"myKey2" :  "my test value 2",
"foo" :  "bar"
}
  1. 配置为在生成项目 (在 VS-> 解决方案资源管理器-> 右键单击文件-> 选择“属性”-> 高级-> 复制到输出目录-> 选择“始终复制”)时将文件复制到输出目录

  2. 在我的项目中安装以下 nuget 包:

    • 微软。扩展。配置。 Json
  3. 将以下内容添加到 程序(或 Main()所在位置) :

    static void Main(string[] args)
    {
    var builder = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json");
    
    
    var configuration = builder.Build();
    
    
    // rest of code...
    }
    
  4. Then read the values using either of the following ways:

    string myKey1 = configuration["myKey1"];
    Console.WriteLine(myKey1);
    
    
    string foo = configuration.GetSection("foo").Value;
    Console.WriteLine(foo);
    

More info: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration?tabs=basicconfiguration#simple-configuration

如果您使用 Microsoft.Extensions.Hosting(版本2.1.0 +)来托管您的控制台应用程序和 asp.net 核心应用程序,那么您的所有配置都注入了 HostBuilderConfigureAppConfigurationConfigureHostConfiguration方法。下面是关于如何添加 appsettings.json和环境变量的演示:

    var hostBuilder = new HostBuilder()
.ConfigureHostConfiguration(config =>
{
config.AddEnvironmentVariables();


if (args != null)
{
// enviroment from command line
// e.g.: dotnet run --environment "Staging"
config.AddCommandLine(args);
}
})
.ConfigureAppConfiguration((context, builder) =>
{
var env = context.HostingEnvironment;
builder.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("appsettings.json", optional: false)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
// Override config by env, using like Logging:Level or Logging__Level
.AddEnvironmentVariables();


})
... // add others, logging, services
//;

为了编译上面的代码,您需要添加这些包:

<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.CommandLine" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="2.1.0" />

对于一个 dotnet 2. x 核心控制台应用来说,它是这样的:

        using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;


[...]
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
var serviceProvider = new ServiceCollection()
.AddLogging(options => options.AddConfiguration(configuration).AddConsole())
.AddSingleton<IConfiguration>(configuration)
.AddSingleton<SomeService>()
.BuildServiceProvider();
[...]
await serviceProvider.GetService<SomeService>().Start();

您可以在 SomeService中注入 ILoggerFactory、 IConfiguration。

您可以使用 LiteWare 配置库进行此操作。它非常类似于。NET 框架原始的 ConfigurationManager和工程。NET 核心/标准。代码方面,你会得到这样的结果:

string cacheDirectory = ConfigurationManager.AppSettings.GetValue<string>("CacheDirectory");
ulong cacheFileSize = ConfigurationManager.AppSettings.GetValue<ulong>("CacheFileSize");

免责声明: 我是 LiteWare. Configuration 的作者。

只是堆积... 类似于周的帖子。在这里我添加机器名称。

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, builder) =>
{
var env = context.HostingEnvironment;
var hostname = Environment.MachineName;
builder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{hostname}.json", optional: true, reloadOnChange: true);
builder.AddEnvironmentVariables();
if (args != null)
{
builder.AddCommandLine(args);
}
})
.UseStartup<Startup>();
}

在.Net Core 3.1上,我们只需要这样做:

static void Main(string[] args)
{
var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
}

使用 SeriLog 会像这样:

using Microsoft.Extensions.Configuration;
using Serilog;
using System;




namespace yournamespace
{
class Program
{


static void Main(string[] args)
{
var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();


try
{
Log.Information("Starting Program.");
}
catch (Exception ex)
{
Log.Fatal(ex, "Program terminated unexpectedly.");
return;
}
finally
{
Log.CloseAndFlush();
}
}
}
}

每天生成一个文件的 Serilog appsetings.json 部分如下:

  "Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "C:\\Logs\\Program.json",
"rollingInterval": "Day",
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact"
}
}
]
}

安装以下软件包:

  • 微软,扩展,配置
  • 微软。扩展。配置。活页夹
  • 微软。扩展。配置。环境变量
  • 微软。扩展。配置。文件扩展
  • 微软。扩展。配置。 Json

密码:

static void Main(string[] args)
{
var environmentName = Environment.GetEnvironmentVariable("ENVIRONMENT");
Console.WriteLine("ENVIRONMENT: " + environmentName);


var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", false)
.AddJsonFile($"appsettings.{environmentName}.json", true)
.AddEnvironmentVariables();


IConfigurationRoot configuration = builder.Build();
var mySettingsConfig = configuration.Get<MySettingsConfig>();


Console.WriteLine("URL: " + mySettingsConfig.Url);
Console.WriteLine("NAME: " + mySettingsConfig.Name);


Console.ReadKey();
}

MySettingsConfig 类:

public class MySettingsConfig
{
public string Url { get; set; }
public string Name { get; set; }
}

您的应用程序设置可以像下面这样简单: enter image description here

另外,如果更新的话,将 appsets 文件设置为 Content/Copy: content

如果你用。Netcore 3.1最简单的方法是使用新的配置系统调用静态类 HostCreateDefaultBuilder方法并配置应用程序

public class Program
{
public static void Main(string[] args)
{
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, config) =>
{
IHostEnvironment env = context.HostingEnvironment;
config.AddEnvironmentVariables()
// copy configuration files to output directory
.AddJsonFile("appsettings.json")
// default prefix for environment variables is DOTNET_
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddCommandLine(args);
})
.ConfigureServices(services =>
{
services.AddSingleton<IHostedService, MySimpleService>();
})
.Build()
.Run();
}
}


class MySimpleService : IHostedService
{
public Task StartAsync(CancellationToken cancellationToken)
{
Console.WriteLine("StartAsync");
return Task.CompletedTask;
}


public Task StopAsync(CancellationToken cancellationToken)
{
Console.WriteLine("StopAsync");
return Task.CompletedTask;
}
}

对于文件 appsettings.jsonappsettings.{environment}.json,您需要将 Copy 设置为 Output Directory = “ Copy if new” 你也可以设置环境变量{前缀} ENVIRONMENT (默认前缀是 DOTNET)以允许选择特定的配置参数。

. csproj 文件:

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<RootNamespace>ConsoleApplication3</RootNamespace>
<AssemblyName>ConsoleApplication3</AssemblyName>
</PropertyGroup>


<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="3.1.7" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.7" />
</ItemGroup>


<ItemGroup>
<None Update="appsettings.Development.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

详情

其他解决方案可以工作,但不能在其他服务中注入 IConfigurationRoot。我只是这样做:

然后安装 Microsoft.Extensions.Configuration.Json

static void Main(string[] args)
{
var serviceProvider = new ServiceCollection()
.AddSingleton(_ =>
new ConfigurationBuilder()
.SetBasePath(Path.Combine(AppContext.BaseDirectory))
.AddJsonFile("appsettings.json", optional: true)
.Build())
.BuildServiceProvider();


// Rest of code ...
}

在其他服务中注入或使用

serviceProvider.GetService<IConfigurationRoot>()