【发布时间】:2019-10-30 17:39:24
【问题描述】:
编辑:如果它在控制台应用程序中运行,则从 ASP.NET 控制器传递配置将不起作用。
背景:
- DLL 将随不同的应用程序、一些控制台、一些 ASP.NET MVC 和一些 WebAPI 一起提供
- 我正在构建一个 .NET Core C# 处理 DLL,它需要 appsettings.json 中的多个配置条目。
- 为简单起见,如果可能,我想将 DLL C# 方法全部设为静态。
- 一个示例配置条目将是“SxProcFull”,其值为 true 或 false。 DLL 需要大约 10 个配置项
- DLL 是更大代码库的一部分,从 Web 控制器方法或控制台应用程序的主要方法向下调用多个级别
如何从 DLL 中获取配置条目?
Web 上的大多数示例都是针对 ASP.NET 的,并且通过将配置入口代码放在控制器方法中并将配置服务传递到控制器方法中来过度简化。
.NET Core 文档详细介绍了存在哪些类型的提供程序,但缺少实际示例。
相关链接:
Understanding .net Core Dependency Injection in a console app
https://espressocoder.com/2018/12/03/build-a-console-app-in-net-core-like-a-pro/
https://blog.bitscry.com/2017/05/30/appsettings-json-in-net-core-console-app/
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/?view=aspnetcore-3.0&tabs=windows
还有更多...
编辑:将多应用类型项目移动到背景列表的顶部。
回答:
using System;
using System.IO;
using System.Reflection;
using Microsoft.Extensions.Configuration;
namespace AspNetCoreTestProject2
{
public static class MyConfiguration
{
private static IConfigurationRoot GetConfigRoot()
{
var assemblyLoc = Assembly.GetExecutingAssembly().Location;
var directoryPath = Path.GetDirectoryName(assemblyLoc);
var configFilePath = Path.Combine(directoryPath, "appsettings.json");
if (File.Exists(configFilePath) == false)
{
throw new InvalidOperationException("Config file not found");
}
IConfigurationBuilder builder = new ConfigurationBuilder();
builder.AddJsonFile(configFilePath);
var configRoot = builder.Build();
return configRoot;
}
public static string ConfigGetConnectionStringByName(string connnectionStringName)
{
if (string.IsNullOrWhiteSpace(connnectionStringName))
{
throw new ArgumentException(nameof(connnectionStringName));
}
var root = GetConfigRoot();
var ret = root.GetConnectionString(connnectionStringName);
if (string.IsNullOrWhiteSpace(ret))
{
throw new InvalidOperationException("Config value cannot be empty");
}
return ret;
}
public static string ConfigEntryGet(string configEntryName)
{
if (string.IsNullOrWhiteSpace(configEntryName))
{
throw new ArgumentException(nameof(configEntryName));
}
var root = GetConfigRoot();
var ret = root[configEntryName];
if (string.IsNullOrWhiteSpace(ret))
{
throw new InvalidOperationException("Config value cannot be empty");
}
return ret;
}
}
}
【问题讨论】:
-
配置项都是简单的键值对,没有复杂的结构。
-
看看这个answer
-
感谢 Matt G。我已根据您链接到的 StackOverflow 问题添加了一个可行的解决方案。
-
生产代码会做更多的验证和异常处理。我还将添加一个 MyConfig C# 包装器类,其中包含用于验证条目的各个条目的方法,以便具有“true”或“false”值的配置条目将接受“true”、“false”、“True”, “假”、“真”、...
-
这样可以避免用户为桌面应用程序编辑配置文件失败。
标签: c# .net-core console-application