简体   繁体   English

.Net核心/控制台应用程序/配置/ XML

[英].Net Core / Console Application / Configuration / XML

My first little venture into the .Net Core libraries using the new ConfigurationBuilder, and Options pattern. 我第一次尝试使用新的ConfigurationBuilder和Options模式进入.Net Core库。

Lot's of good examples here: https://docs.asp.net/en/latest/fundamentals/configuration.html and a good copy of the example here 很好的例子地块的位置: https://docs.asp.net/en/latest/fundamentals/configuration.html和示例的一个良好的副本这里

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. 第1项。它说这可以用于非MVC应用程序,但没有关于如何在没有MVC的情况下使用它的示例 - 特别是如果您使用的是自定义的强类型类。 I would like to see an example of showing the setup of DependencyInjection, Configuration, and Logging using a Console application . 我想看一个使用控制台应用程序显示DependencyInjection,Configuration和Logging设置的示例

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. 第2项。它表示您可以回写,但没有关于如何将任何更改保留回文件存储的示例或文档。 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? 在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). 第3项。所有示例都需要手动轰炸的初始文件 - 希望看到一个示例,其中初始json / xml文件是从强类型类创建的 (当应用程序有许多参数时会派上用场)。

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. 如果您知道有助于我的帖子/文档,我将不胜感激。

How do I configure a .NET Core 1.0.0 Console Application for Dependency Injection, Logging and Configuration? 如何为依赖注入,日志记录和配置配置.NET Core 1.0.0控制台应用程序?

A lot of what was written is deprecated after RC2. 在RC2之后,很多写的内容都被弃用了。 (see issue ). (见问题 )。 Fortunatelly there are some updated posts with excelent info: Fortunatelly有一些更新的帖子,有很多信息:

Essential .NET - Dependency Injection with .NET Core Essential .NET - 使用.NET Core进行依赖注入

Essential .NET - Logging with .NET Core Essential .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. 我打赌有些东西可以改进,请留下评论,以便我可以改进这个答案。

In my static void Main , I 在我的static void Main ,我

  • Setup Dependency injection 设置依赖注入
  • Invoke ConfigureServices 调用ConfigureServices
  • Instantiate my Application class using DI 使用DI实例化我的Application
  • Switch from 'sync Main' to ' async Application.Run()' (It makes sense to me to switch to async as soon as possible and only once.) 从'sync Main'切换到' async Application.Run()'(对我来说,尽快切换到异步并且只有一次是有道理的。)

On my Application Class: 在我的Application类:

  • I inject as much as possible on the class constructor. 我尽可能多地注入类构造函数。
  • Catch any exception on the Run() method. 捕获Run()方法上的任何异常。

Here is the code. 这是代码。

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());
        }
    }
}
}

The AppSettings.json file: AppSettings.json文件:

{
  "MyOptions": {
    "Name" : "John"
  }
}

And the project.json file: 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",

On your question #2: I've read the document and unless I am missing something, it does not says you can write configuration. 关于你的问题#2:我已阅读该文档,除非我遗漏了某些内容,否则它不会说您可以编写配置。 I'm not sure you can do that, unless you edit the JSON files manually using Newtonsoft.JSON. 除非您使用Newtonsoft.JSON手动编辑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. 这意味着当再次读取源时,写入的值将丢失。

For your question #3 I've included a default AppSettings.json file. 对于您的问题#3,我已经包含了一个默认的AppSettings.json文件。 Your config should have a Section where its settings match by name to the public properties of your settings class. 您的配置应该有一个部分,其设置与名称匹配您的设置类的公共属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM