.Net Core/控制台应用程序/配置/XML [英] .Net Core / Console Application / Configuration / XML

查看:40
本文介绍了.Net Core/控制台应用程序/配置/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 的情况下使用它的示例 - 特别是如果您使用自定义的强类型类.我想看一个使用控制台应用程序设置依赖注入、配置和日志记录的示例.

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?

Item 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 之后,很多内容都被弃用了.(请参阅问题).幸运的是,有一些更新的帖子提供了很好的信息:

A lot of what was written is deprecated after RC2. (see issue). Fortunatelly there are some updated posts with excelent info:

Essential .NET - .NET Core 依赖注入

基本 .NET - 使用 .NET Core 进行日志记录

我想出了以下解决方案.我敢打赌,有些事情可以改进,请发表评论,以便我改进此答案.

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.

在我的 static void Main 中,我

  • 设置依赖注入
  • 调用ConfigureServices
  • 使用 DI 实例化我的 Application
  • 从同步主"切换到异步 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.)

在我的 Application 类上:

  • 我在类构造函数中尽可能多地注入.
  • 捕获 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:我已经阅读了文档,除非我遗漏了什么,否则它并没有说你可以编写配置.我不确定您是否可以这样做,除非您使用 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 文件.您的配置应该有一个部分,其中的设置按名称与设置类的公共属性匹配.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆