Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using app.config in .Net Core

Tags:

c#

.net-core

I have problem. I need to write a program in .Net Core(C#) which use app.config like this:

<?xml version="1.0" encoding="utf-8" ?> <configuration>   <configSections>     <section name="custom" type="ConfigurationSample.CustomConfigurationSection, ConfigurationSample"/>   </configSections>   <connectionStrings>     <add name="sampleDatabase" connectionString="Data Source=localhost\SQLExpress;Initial Catalog=SampleDatabase;Integrated Security=True"/>   </connectionStrings>   <appSettings>     <add key="sampleApplication" value="Configuration Sample"/>   </appSettings>   <custom>     <customConfigurations>       <add key="customSample" name="Mickey Mouse" age="83"/>     </customConfigurations>   </custom> </configuration> 

and I write:

string connectionString = ConfigurationManager.ConnectionStrings["sampleDatabase"].ConnectionString; Console.WriteLine(connectionString);  // read appSettings configuration string appSettingValue = ConfigurationManager.AppSettings["sampleApplication"]; Console.WriteLine(appSettingValue); 

and it is example from the internet so I thought would work, but I am getting exceptions:

System.Configuration.ConfigurationErrorsException: 'Error Initializing the configuration system.' Inner Exception TypeLoadException: Could not load type 'System.Configuration.InternalConfigurationHost' from assembly 'CoreCompat.System.Configuration, Version=4.2.3.0, Culture=neutral, PublicKeyToken=null' because the method 'get_bundled_machine_config' has no implementation (no RVA). 

I downloaded via NuGet - Install-Package CoreCompat.System.Configuration -Version 4.2.3-r4 -Pre and still don't work. Maybe someone can help me?

like image 233
Nju Avatar asked Jul 11 '17 11:07

Nju


People also ask

Does .NET Core use web config?

ASP.NET Core places all startup logic for the application in a single file, in which the necessary services and dependencies can be defined and configured. It replaces the web. config file with a flexible configuration feature that can leverage a variety of file formats, such as JSON, as well as environment variables.

How do I configure ASP NET Core configuration?

Configuration in ASP.NET Core is performed using one or more configuration providers. Configuration providers read configuration data from key-value pairs using a variety of configuration sources: Settings files, such as appsettings.json. Environment variables.

How do I create a web application using NET Core?

Select the ".Net Core" and "ASP.NETCore 3.1" version and then select "Web application" as a project template. Select the appsettings.json file and add the configuration settings.

What is app config in Visual Studio?

When you create a (non-web) .NET Framework application in Visual Studio, an app.config file is added to your project. When you create a class library or a .NET Core project, such a file is not included, although it can be done afterward. In a web project (i.e. ASP.NET) you will use a similar file, the web.config.

How to read app config configuration file?

Actually, app.config configuration file was an XML file. So you can read settings from it using XML configuration provider ( source on github, nuget link ). But keep in mind, it will be used only as a configuration source - any logic how your app behaves should be implemented by you.


2 Answers

It is possible to use your usual System.Configuration even in .NET Core 2.0 on Linux. Try this test example:

  1. Created a .NET Standard 2.0 Library (say MyLib.dll)
  2. Added the NuGet package System.Configuration.ConfigurationManager v4.4.0. This is needed since this package isn't covered by the meta-package NetStandard.Library v2.0.0 (I hope that changes)
  3. All your C# classes derived from ConfigurationSection or ConfigurationElement go into MyLib.dll. For example MyClass.cs derives from ConfigurationSection and MyAccount.cs derives from ConfigurationElement. Implementation details are out of scope here but Google is your friend.
  4. Create a .NET Core 2.0 app (e.g. a console app, MyApp.dll). .NET Core apps end with .dll rather than .exe in Framework.
  5. Create an app.config in MyApp with your custom configuration sections. This should obviously match your class designs in #3 above. For example:

<?xml version="1.0" encoding="utf-8"?> <configuration>   <configSections>     <section name="myCustomConfig" type="MyNamespace.MyClass, MyLib" />   </configSections>   <myCustomConfig>     <myAccount id="007" />   </myCustomConfig> </configuration> 

That's it - you'll find that the app.config is parsed properly within MyApp and your existing code within MyLib works just fine. Don't forget to run dotnet restore if you switch platforms from Windows (dev) to Linux (test).

Additional workaround for test projects

If you're finding that your App.config is not working in your test projects, you might need this snippet in your test project's .csproj (e.g. just before the ending </Project>). It basically copies App.config into your output folder as testhost.dll.config so dotnet test picks it up.

  <!-- START: This is a buildtime work around for https://github.com/dotnet/corefx/issues/22101 -->   <Target Name="CopyCustomContent" AfterTargets="AfterBuild">     <Copy SourceFiles="App.config" DestinationFiles="$(OutDir)\testhost.dll.config" />   </Target>   <!-- END: This is a buildtime work around for https://github.com/dotnet/corefx/issues/22101 --> 
like image 55
DeepSpace101 Avatar answered Sep 27 '22 18:09

DeepSpace101


  1. You can use Microsoft.Extensions.Configuration API with any .NET Core app, not only with ASP.NET Core app. Look into sample provided in the link, that shows how to read configs in the console app.

  2. In most cases, the JSON source (read as .json file) is the most suitable config source.

    Note: don't be confused when someone says that config file should be appsettings.json. You can use any file name, that is suitable for you and file location may be different - there are no specific rules.

    But, as the real world is complicated, there are a lot of different configuration providers:

    • File formats (INI, JSON, and XML)
    • Command-line arguments
    • Environment variables

    and so on. You even could use/write a custom provider.

  3. Actually, app.config configuration file was an XML file. So you can read settings from it using XML configuration provider (source on github, nuget link). But keep in mind, it will be used only as a configuration source - any logic how your app behaves should be implemented by you. Configuration Provider will not change 'settings' and set policies for your apps, but only read data from the file.

like image 36
Set Avatar answered Sep 27 '22 20:09

Set