【问题标题】:App.config values not read/detected in .Net Core 2.2 class library project.Net Core 2.2 类库项目中未读取/检测到 App.config 值
【发布时间】:2020-03-20 13:53:25
【问题描述】:

我正在 .net core 2.2 中创建类库项目,该项目可用于 .net core 和 .net framework。

由于是类库项目,我添加了 app.config 来读取配置值。从 Nuget 包安装 ConfigurationManger。下面是app.config文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="InputKey" value="12345" />
  </appSettings>
</configuration>

.Net 代码读取如下值,

INPUT_KEY = ConfigurationManager.AppSettings["InputKey"];

添加了 Nunit 测试项目并在那里添加了 app.config。项目构建成功。当我调试我的测试用例时,下面的行总是返回 null。

  1. 始终尝试复制 app.config(类库和测试项目)并将 Nunit 测试项目设置为启动项目 - 不工作。
  2. 从类库项目中删除了 app.config[![在此处输入图像描述][1]][1],仅保留了测试项目 app.config- 无法正常工作。
  3. 将类库设置为启动项目 - 不工作。

【问题讨论】:

  • 这不应该是来自网络标准 2+ 的“appsettings.json”吗?
  • 如果我使用 appsettings.json,我可以将这个类库用于 .Net 框架项目吗?
  • github.com/dotnet/corefx/issues/22101 我在 Nunit 测试项目的 .csproj 中有上述内容,它可以工作。如果其他一些 .net 框架应用程序想要使用这个类库,他们是否也需要在那里添加上面的代码?我的偏好是他们只需要引用 dll 并使用它。
  • @Govind 所有 Microsoft.Extensions.* 包都是 .NET Standard 2.0,因此您可以在任何地方使用它们。无论如何,您不需要使用appsettings.json,Configuration 包可以与多个提供程序一起使用。实际上,您可能应该使用配置类和 Secrets 功能来保护开发过程中的输入密钥
  • @Govind 如果您想在两个运行时中使用您的项目而不会出现问题或警告,它必须是 .NET Standard。这与配置无关。 .NET 核心 2.2。具有 .NET Framework 中不存在的 API。当您从 .NET Framework 项目引用 .NET Core 程序集时,您的编译器应该已经在抱怨

标签: c# asp.net-core .net-core .net-core-2.2


【解决方案1】:
<Target Name="CopyCustomContent" AfterTargets="AfterBuild"> 
<Copy SourceFiles="app.config" DestinationFiles="$(OutDir)\testhost.dll.config" /> 
</Target>

在 .csproj 文件中添加上述代码解决了我的问题。

由于我的要求是在 .net framework 和 .net core 中都使用 dll,所以我必须使用 .Net Standard 而不是 .netcore 或 .netframework 创建项目。

感谢@Panagiotis Kanavos 的建议。

【讨论】:

    【解决方案2】:

    你可以查看我的帖子here

    旁注:此方法适用于 json 文件

    先安装这两个包

    Install-Package Microsoft.Extensions.Options
    Install-Package Microsoft.Extensions.DependencyInjection
    

    在您的代码中

    public static void Main()
    {
        var serviceCollection = new ServiceCollection();
        ConfigureServices(serviceCollection);
    }
    
    private static void ConfigureServices(IServiceCollection serviceCollection)
    {
          var currentDir = ProjectPath.GetApplicationRoot();
    
         // build configuration
         varconfiguration = newConfigurationBuilder()
                   .SetBasePath(currentDir)
                   .AddJsonFile("appsettings.json",false)
                   .Build();
    
         serviceCollection.AddOptions();
         serviceCollection.Configure<WebJobSettings>(configuration.GetSection("WebJobSettings"));
         // add app
         serviceCollection.AddTransient<WebJob>();
    }
    

    那么就这样读

    public class WebJob
    {
      private readonly IOptions<WebJobSettings> _webJobSettings;
      public WebJob(
        IOptions<WebJobSettings> webJobSettings)
      {
        _webJobSettings = webJobSettings;
      } 
    }
    

    【讨论】:

    • 是的,但相同的 dll 是否适用于 .net 框架?
    • 这是 .net 核心,所以我认为它不适用于 .net
    【解决方案3】:

    首先将配置文件排除在单元测试之外!改为使用模拟来传递配置值。这有几个优点:

    • 您将能够测试不同的配置值集,而不仅仅是当前配置文件中的那些
    • 您将能够针对无效输入测试配置值
    • 您不必记住始终维护配置文件的另一个工作副本
    • 更简洁的架构:单元测试通常不应该接触物理文件,而只测试类的行为

    下面的代码是关于如何使用模拟为单元测试提供配置值的建议:

    // The class that is accessed in order to get some config setting
    public class AppConfig
    {
        // The provider reads from a physical file when your lib is shipped but in your tests it will be mocked 
        private readonly AppConfigProvider provider;
    
        // Constructor used by your app or library
        public AppConfig() : this(new AppConfigProvider())
        {
        }
    
        // Constructor that can be used by your unit testing framework to inject a mock
        internal AppConfig(AppConfigProvider provider)
        {
            this.provider = provider;
        }
    
        public string InputKey => GetConfigValueOrThrow("InputKey");
    
        private string GetConfigValueOrThrow(string configKey)
        {
            string value = provider.GetSetting(configKey);
    
            if (value == null)
                throw new Exception($"A value for key {configKey} is missing in the App.config file.");
    
            return value;
        }
    }
    
    // Provider implementation that actually reads from the app.config file
    internal class AppConfigProvider
    {
        internal virtual string GetSetting(string configKey)
        {
            return ConfigurationManager.AppSettings[configKey];
        }
    }
    
    // In the test class the config values will be returned by a mock instead of a physical file. This example uses Moq as mocking framework.
    public class AppConfigTest
    {
        private Mock<AppConfigProvider> mock;
        private AppConfig appConfig;
    
        [SetUp]
        public void Setup()
        {
            mock = new Mock<AppConfigProvider>();
            appConfig = new AppConfig(mock.Object);
        }
    
        [Test]
        public void TestInputKeyWhenValueIsValid()
        {
            mock.Setup(provider => provider.GetSetting("InputKey")).Returns("12345");
    
            Assert.AreEqual("12345", appConfig.InputKey);
        }
    
    }
    

    【讨论】:

    • 嘲讽是的,我能做到。但我的要求不是这样。我只想复制其他第 3 方消费者如何使用我的 dll 进行访问。因为我想将它用于.net框架,.net核心和其他平台它应该与较低版本兼容。我的问题不是如何模拟 app.config。相反,我问的是如何访问 app.config。
    猜你喜欢
    • 1970-01-01
    • 2012-04-09
    • 2017-02-09
    • 2018-05-24
    • 2018-07-17
    • 2018-12-11
    • 2014-04-19
    • 2010-12-17
    • 2011-07-30
    相关资源
    最近更新 更多