ASP.NET Core支持新的配置系统,如下所示: https://docs.asp.net/en/latest/fundamentals/configuration.html
.NET Core控制台应用程序是否也支持此模型?
如果不是之前的app.config
和ConfigurationManager
型号的替代品?
答案 0 :(得分:154)
对于.NET Core 2.0控制台应用程序,我执行了以下操作:
{ "myKey1" : "my test value 1", "myKey2" : "my test value 2", "foo" : "bar" }
配置在构建项目时将文件复制到输出目录(在VS - >解决方案资源管理器 - >右键单击文件 - >选择'属性' - >高级 - >复制到输出目录 - >选择'始终复制')
在我的项目中安装以下nuget包:
将以下内容添加到 Program.cs (或Main()
所在的位置):
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
var configuration = builder.Build();
// rest of code...
}
然后使用以下任一方式读取值:
string myKey1 = configuration["myKey1"];
Console.WriteLine(myKey1);
string foo = configuration.GetSection("foo").Value;
Console.WriteLine(foo);
答案 1 :(得分:56)
您可以使用此代码段。它包括配置和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"
]
},
...
}
答案 2 :(得分:14)
如果您使用Microsoft.Extensions.Hosting
(版本2.1.0+)来托管您的控制台应用和asp.net核心应用,则所有配置都会注入HostBuilder
的{{1}}和{ {1}}方法。以下是有关如何添加ConfigureAppConfiguration
和环境变量的演示:
ConfigureHostConfiguration
为了编译上面的代码,你需要添加这些包:
appsettings.json
答案 3 :(得分:9)
我错了。您可以使用netcore控制台应用程序中的新ConfigurationBuilder
。
有关示例,请参阅https://docs.asp.net/en/latest/fundamentals/configuration.html。
但是,只有aspnet核心具有开箱即用的依赖注入,因此您无法使用强类型配置设置并使用IOptions
自动注入它们。
答案 4 :(得分:7)
在.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"
}
}
]
}
答案 5 :(得分:3)
如果使用.netcore 3.1,最简单的方法是使用新的配置系统来调用静态类type ShapeTypeBad<U> = Shape extends any ? U extends Shape ? Shape : never : never;
type tBad = ShapeTypeBad<typeof shapeNarrow> // ShapeOne | ShapeTwo ?
的{{1}}方法并配置应用程序
CreateDefaultBuilder
您需要为文件Host
和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;
}
}
设置“复制到输出目录” =“如果更新则复制”
您还可以设置环境变量{prefix} ENVIRONMENT(默认前缀为DOTNET )以允许选择特定的配置参数。
.csproj文件:
appsettings.json
更多详细信息.NET Generic Host
答案 6 :(得分:1)
您可以使用LiteWare.Configuration库。它与.NET Framework的原始ConfigurationManager
非常相似,并且适用于.NET Core / Standard。在代码方面,您最终会得到类似的东西:
string cacheDirectory = ConfigurationManager.AppSettings.GetValue<string>("CacheDirectory");
ulong cacheFileSize = ConfigurationManager.AppSettings.GetValue<ulong>("CacheFileSize");
免责声明:我是LiteWare.Configuration的作者。
答案 7 :(得分: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。
答案 8 :(得分:0)
只是堆积……类似于周飞宇的帖子。在这里,我要添加机器名称。
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>();
}
答案 9 :(得分:0)
安装以下软件包:
代码:
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; }
}
答案 10 :(得分:0)
其他解决方案有效,但不适用于您想在其他服务中注入 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>()
答案 11 :(得分:-1)
var directoryInfo = Directory.GetParent(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName).FullName;
var builder = new ConfigurationBuilder()
.SetBasePath(directoryInfo)
.AddJsonFile("appsettings.json", true, true)
.Build();