.Net Core /控制台应用程序/配置/ XML [英] .Net Core / Console Application / Configuration / XML
问题描述
我第一次使用新的ConfigurationBuilder和Options模式进入.Net Core库。
My first little venture into the .Net Core libraries using the new ConfigurationBuilder, and Options pattern.
这里有很多很好的例子: https://docs.asp.net/en/latest/fundamentals/configuration.html
和示例的完整副本此处
Lot's of good examples here: https://docs.asp.net/en/latest/fundamentals/configuration.html and a good copy of the example here
第1项。它说可以在非MVC应用程序中使用,但是没有在没有MVC的情况下如何使用它的示例-特别是如果您正在使用自定义的强类型类。 我想看一个使用控制台应用程序显示DependencyInjection,配置和日志记录设置的示例。
Item 1. it says this can be used with non MVC applications, but no examples on how to use it without MVC - particularly if you are using a custom, strongly-typed class. I would like to see an example of showing the setup of DependencyInjection, Configuration, and Logging using a Console application.
第2项,它说您可以写回,但没有任何示例或文档可以说明如何将任何更改持久保存回文件存储。 我想看一个示例,说明如何使用强类型的类将持久性更改回配置。在Json或XML中?
Item 2. it says you can write back, but no examples or documentation as to how to persist any changes back to the file store. I would like to see an example of how persist changes back into the configuration using a strongly typed class. In both Json or XML?
项目3。所有示例都需要手动轰炸初始文件-想看一个示例,其中初始json / xml文件是从强类型类创建的()(当应用程序有很多参数时会派上用场)。
Item 3. all examples require a hand bombed initial file - would like to see an example where the initial json/xml file is created from a strongly-typed class (comes in handy when there are many parameters for the application).
如果我可以花足够的时间为此(而不是重新发布文档中已有的示例),我会做的! 如果您知道对我有帮助的帖子/文档,我将不胜感激。
If I can spend enough time on this (rather than re-post an example already in the documentation) I'll do it! If you know of a post/documentation that will help me, I would appreciate it.
推荐答案
我如何配置.NET Core 1.0.0控制台应用程序以进行依赖关系注入,日志记录和配置?
写的很多东西RC2之后不推荐使用。 (请参见问题)。
Fortunatelly有一些具有出色信息的更新帖子:
A lot of what was written is deprecated after RC2. (see issue). Fortunatelly there are some updated posts with excelent info:
我想出了以下解决方案。我敢打赌有些事情可以改善,请留下评论,以便我改善这个答案。
I came up with the following solution. I bet there are things that can be improved, please leave comments so I can improve this answer.
在我的静态void Main $ c中$ c>,我
- 设置依赖项注入
- 调用
ConfigureServices
- 使用DI实例化我的
Application
类 - 从同步Main到 异步 Application.Run()
(对我来说,尽快且仅一次切换到异步是很有意义的。)
- Setup Dependency injection
- Invoke
ConfigureServices
- Instantiate my
Application
class using DI - Switch from 'sync Main' to 'async Application.Run()' (It makes sense to me to switch to async as soon as possible and only once.)
在我的应用程序上
类:
- 我尽可能在类构造函数上注入。
- 在Run()方法上捕获任何异常。
这里是代码。
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Configuration;
using System.IO;
public class Program
{
static void Main(string[] args)
{
IServiceCollection serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
// Application application = new Application(serviceCollection);
IServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();
var app = serviceProvider.GetService<Application>();
// For async
Task.Run(() => app.Run()).Wait(); // Exceptions thrown here will be lost! Catch them all at Run()
// Otherwise use sync as in: app.Run();
}
private static void ConfigureServices(IServiceCollection services)
{
ILoggerFactory loggerFactory = new LoggerFactory()
.AddConsole()
.AddDebug();
services.AddSingleton(loggerFactory); // Add first my already configured instance
services.AddLogging(); // Allow ILogger<T>
IConfigurationRoot configuration = GetConfiguration();
services.AddSingleton<IConfigurationRoot>(configuration);
// Support typed Options
services.AddOptions();
services.Configure<MyOptions>(configuration.GetSection("MyOptions"));
services.AddTransient<Application>();
}
private static IConfigurationRoot GetConfiguration()
{
return new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile($"appsettings.json", optional: true)
.Build();
}
}
public class MyOptions
{
public string Name { get; set; }
}
public class Application
{
ILogger _logger;
MyOptions _settings;
public Application(ILogger<Application> logger, IOptions<MyOptions> settings)
{
_logger = logger;
_settings = settings.Value;
}
public async Task Run()
{
try
{
_logger.LogInformation($"This is a console application for {_settings.Name}");
}
catch (Exception ex)
{
_logger.LogError(ex.ToString());
}
}
}
}
AppSettings.json文件:
The AppSettings.json file:
{
"MyOptions": {
"Name" : "John"
}
}
和 project.json
文件:
"dependencies": {
"Microsoft.Extensions.Configuration": "1.0.0",
"Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
"Microsoft.Extensions.Configuration.Json": "1.0.0",
"Microsoft.Extensions.DependencyInjection": "1.0.0",
"Microsoft.Extensions.Logging": "1.0.0",
"Microsoft.Extensions.Logging.Console": "1.0.0",
"Microsoft.Extensions.Logging.Debug": "1.0.0",
"Microsoft.Extensions.Options": "1.0.0",
"Microsoft.Extensions.PlatformAbstractions": "1.0.0",
"Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
关于您的问题2:我已经阅读了文档,然后解开ss我缺少了一些东西,它并不表示您可以编写配置。我不确定您是否可以这样做,除非您使用Newtonsoft.JSON手动编辑JSON文件。
On your question #2: I've read the document and unless I am missing something, it does not says you can write configuration. I'm not sure you can do that, unless you edit the JSON files manually using Newtonsoft.JSON.
如果
名称/值对已写入配置,但不保留。
表示再次读取源
时,书面价值将丢失。
If a name/value pair is written to Configuration, it is not persisted. This means that the written value will be lost when the sources are read again.
对于您的问题#3我包含一个默认的AppSettings.json文件。您的配置应包含一个Section,其设置通过名称与您的设置类的公共属性匹配。
For your question #3 I've included a default AppSettings.json file. Your config should have a Section where its settings match by name to the public properties of your settings class.
这篇关于.Net Core /控制台应用程序/配置/ XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!