Reading settings from app.config or web.config in

2019-01-03 01:03发布

I'm working on a C# class library that needs to be able to read settings from the web.config or app.config file (depending on whether the DLL is referenced from an ASP.NET web application or a Windows Forms application).

I've found that

ConfigurationSettings.AppSettings.Get("MySetting")

works, but that code has been marked as deprecated by Microsoft.

I've read that I should be using:

ConfigurationManager.AppSettings["MySetting"]

However, the System.Configuration.ConfigurationManager class doesn't seem to be available from a C# Class Library project.

Does anyone know what the best way to do this is?

20条回答
Viruses.
2楼-- · 2019-01-03 01:31

I always create an IConfig interface with typesafe properties declared for all configuration values. A Config implementation class then wrappers the calls to System.Configuration. All your System.Configuration calls are now in one place so much easier and cleaner to maintain and track which fields are being used and declare their default values. I write a set of private helper methods to read and parse common data types.

Using an IoC framework you can access the IConfig fields anywhere your in app by simply passing the interface to a class constructor. You're also then able to create mock implementations of the IConfig interface in your unit tests so you can now test various configuration values and value combinations without needing to touch your App.config or Web.config file.

查看更多
Summer. ? 凉城
3楼-- · 2019-01-03 01:32

You might be adding the App.config file to a DLL. App.Config works only for executable projects, since all the dll take the configuration from the configuration file for the exe being executed.

Let's say you have two projects in your solution:

  • SomeDll
  • SomeExe

Your problem might be releated to the fact that you're including the app.config to SomeDLL and not SomeExe. SomeDll is able to read the configuration from the SomeExe project.

查看更多
登录 后发表回答