ASP.NET Core支持一个新的配置系统,如下所示:https : //docs.asp.net/en/latest/fundamentals/configuration.html
.NET Core控制台应用程序也支持此模型吗?
如果没有什么是替代以前的app.config
和ConfigurationManager
模式?
ASP.NET Core支持一个新的配置系统,如下所示:https : //docs.asp.net/en/latest/fundamentals/configuration.html
.NET Core控制台应用程序也支持此模型吗?
如果没有什么是替代以前的app.config
和ConfigurationManager
模式?
Answers:
您可以使用此代码段。它包括配置和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>();
............
}
}
哦,别忘了添加project.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控制台应用程序,我执行了以下操作:
{ "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);
详细信息:https : //docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration?tabs=basicconfiguration#simple-configuration
IConfigurationRoot
在.NET Core 2.0中仍然可用。它继承自,IConfiguration
但被认为是它的派生案例,并不常用。无论如何,代码示例已更新为不包含它,并避免了任何混乱。
如果您使用Microsoft.Extensions.Hosting
(版本2.1.0+)托管控制台应用程序和asp.net核心应用程序,则所有配置都将带有HostBuilder
的ConfigureAppConfiguration
和ConfigureHostConfiguration
方法。这是有关如何添加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" />
ASPNETCORE_ENVIRONMENT
但是context.HostingEnvironment.EnvironmentName
设置不正确
new HostBuilder()
多余的吗?不HostBuilder
内部全部完成吗?
我错了。您可以ConfigurationBuilder
从netcore控制台应用程序中使用新的。
有关示例,请参见https://docs.asp.net/en/latest/fundamentals/configuration.html。
但是,只有aspnet core具有开箱即用的依赖项注入功能,因此您没有能力使用强类型的配置设置并使用来自动注入它们IOptions
。
Microsoft.Extensions.Options
并致电service.AddOptions();
ConfigureWebHostDefaults()
示例中的调用是可选的,并且仅适用于Web应用程序。
对于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();
您可以在中注入ILoggerFactory,IConfiguration SomeService
。
在.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"
}
}
]
}
您可以为此使用LiteWare.Configuration库。它与.NET Framework的原始版本非常相似,ConfigurationManager
并且适用于.NET Core / Standard。在代码方面,您将得到类似以下内容的结果:
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>();
}
安装以下软件包:
码:
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; }
}
Directory.GetCurrentDirectory()
代替AppContext.BaseDirectory
。之后应该没有必要进行黑客入侵。