Levi Fuller
Levi Fuller

Reputation: 15731

How to use use same configuration between .NET Framework, .NET Standard, and .NET Core project?

Since the ConfigurationManager doesn't exist in .NET Standard, what is the best way to retrieve application settings for the executing assembly, whether it be a web.config or an appSettings.{env}.json, within a .NET standard class library?

We have three projects:

In the .NET Standard class lib, we have a URL which needs to change based on the environment it's deployed to.

This is fine for the .NET Core app, we simply add the URLs to the appropriate appSettings.{env}.json file, add the appropriate values to the DI container, then use the Microsoft.Extensions.Options library to retrieve the configuration.

However, we also need to call the library from our .NET Framework 4.6.1 application, but since there is no method (at least none that I could find) to retrieve the values from a web.config file, we don't have a good way to set the URL within the class library.

We've gotten around this for now by making the URL variable static and setting its value from within the Application_Start() method of each .NET Framework project we reference it from, we determine which environment it is via an appSetting key we added to each web.config, then manually set the URL based on the environment.

Is there a more robust way to handle retrieving appSettings values from both a .NET Core and .NET Framework application within a .NET Standard class library? Preferably where we can set the value solely within the class library.

Upvotes: 5

Views: 1157

Answers (1)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241728

You should read the value from configuration before calling your library, and pass it by parameter, either into a method or constructor.

In general, library code shouldn't depend on side effects from the configuration of its host environment. Doing so makes it very difficult to reuse code, or to test effectively.

Upvotes: 2

Related Questions