In The Olden Days
In a web.config file, settings could be placed in an appSettings section like so:
In 8-2017 Microsoft came out with System.Configuration.Manager
for .NET CORE v4.4. Currently v4.5 and v4.6 preview.
Install this nuget package. Add directive to a code file
using System.Configuration;
Now, you can do your
var val = ConfigurationManager.AppSettings["mysetting"];
There is one trick for web sites though - you no longer use web.config
for application settings and configuration sections. You use app.config
as well as other types of projects. But if you deploy in ISS, you might need to use both. In web.config
you supply strictly ISS-related entries. Your app-specific entries go to app.config
I'm going to assume you're talking about a ASPNET Core project as you specifically mention web.config.
Here's what you need to do.
IOptions<FooSettingsClass>
is usually configured at application start which means that it's available at runtime with code that looks something like this.
// Adds services required for using options.
services.AddOptions();
services.Configure<AppSettings>(Configuration.GetSection("FooAppSettings"));
The easiest way is to have the framework inject it through the constructor. Typically you'll see it (as you mentioned) being injected in the controller like this:
class FooController : Controller {
public FooController(IOptions<FooSettingsClass> settings) { .
//..
}
}
If you need to access this configuration is say, a service, then you simply have a constructor, in a different assembly, which accepts those options. So:
public class SomeServiceInAnotherAssembly {
public SomeServiceInAnotherAssembly(IOptions<FooSettingsClass> settings) {
//..
}
}
This obviously means that your FooSettingsClass
class needs to be outside of your ASPNET Core project (to avoid circular dependencies), but this is one way of propagating your configuration without writing any code, which is what I've seen other developers do. To me, writing code is a hoop jumping solution bound to have bugs.
Don't forget that your class (in this exampe SomeServiceInAnotherAssembly
) needs to be registered at startup, i.e. services.AddScoped<SomeServiceInAnotherAssembly>();
The nice thing about this approach is that it makes your classes testable.