ASP.NET Core 支持新的配置系统,如下所示:https://docs.asp.net/en/latest/fundamentals/configuration.html
.NET Core 控制台应用程序是否也支持此模型?
如果不是的话,用什么替代之前的app.config
和ConfigurationManager
模型?
答案
您可以使用此代码片段。
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"
]
},
...
}