StuffOfInterest
StuffOfInterest

Reputation: 518

Reading from app.config in .NET Core application referencing .NET Standard library

I'm converting over some existing code from .NET Framework to .NET Standard for use in .NET Core apps. The library project has been converted over and is building fine. It contains some database access code that uses EF Core. Due to the legacy nature of the consumers for this code I wanted to continue using the App.Config or Web.Config files with Configuration Manager. To do this I added the System.Configuration.ConfigurationManager NuGet package to the library project.

The library is validated with a unit test project that uses MSTest. The project was targeting .NET Framework 4.7.1, which could consume the .NET Standard 2.0 library package. When targeting .NET Framework, all of the unit tests were passing.

After changing the unit test project to target .NET Core 2.0, the database code is no longer able to find the connection strings stored in the App.Config file of the unit test project. When I debug the test and inspect the ConfigurationManager.ConnectionStrings collection, I only see one defined that appears to be a SQL Express connection likely coming from the Machine.Config file.

Has anyone had success accessing App.Config from a .NET Core app passing through a .NET Standard library with the ConfigurationManager compatibility library?

Upvotes: 1

Views: 2012

Answers (1)

Mo Chavoshi
Mo Chavoshi

Reputation: 565

Still there is a known issue in Microsoft.Net.Test.Sdk and it is because when you use ConfigurationManager in test applications using .Net Core, ConfigurationManager is looking for testhost.dll.config and not your standard assembly config file.

There is a non-pleasant workaround for this issue based on this discussion in github which you can copy your App.Config file into your output directory with name testhost.dll.config by putting this element in your test csproj file:

<Target Name="CopyCustomContent" AfterTargets="AfterBuild">
    <Copy SourceFiles="App.config" DestinationFiles="$(OutDir)\testhost.dll.config" />
</Target>

And then you can use ConfigurationManager.OpenMappedExeConfiguration to load your config file.

ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = "testhost.dll.config";

Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

And for example for reading an appsetting you can do like this:

var setting = Config.AppSettings.Settings[key];

Upvotes: 3

Related Questions