I am trying to learn ASP.NET 5. I am using it on Mac OS X. At this time, I have a config.json file that looks like the following:
config.json
In your Startup
class, first specify your configuration sources:
private readonly IConfiguration configuration;
public Startup(IHostingEnvironment env)
{
configuration = new Configuration()
.AddJsonFile("config.json")
.AddJsonFile($"config.{env.EnvironmentName}.json", optional: true);
}
The env.EnvironmentName
is something like "development"
or "production"
. Suppose it is "development"
. The framework will try to pull configuration values from config.development.json
first. If the requested values aren't there, or the config.development.json
file doesn't exist, then the framework will try to pull the values from config.json
.
Configure your config.json
sections as services like this:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(configuration.GetSubKey("AppSettings"));
services.Configure<DbSettings>(configuration.GetSubKey("DbSettings"));
services.Configure<EmailSettings>(configuration.GetSubKey("EmailSettings"));
}
Calling Configure<T>(IConfiguration)
on the IServiceCollection
registers the type IOptions<T>
in the dependency injection container. Note that you don't need your AppConfiguration
class.
Then specify dependencies to be injected like this:
public class EmailController : Controller
{
private readonly IOptions<EmailSettings> emailSettings;
public EmailController (IOptions<EmailSettings> emailSettings)
{
this.emailSettings = emailSettings;
}
public IActionResult Index()
{
string apiKey = emailSettings.Options.EmailApiKey;
...
}
}
Try use OptionsModel
. it allows strong typed model binding to configuration.
class AppSettings
{
public string SomeSetting {get;set;}
}
var configuration = new Configuration().AddJsonFile("config.json");
var opt = ConfigurationBinder.Bind<AppSettings>(configuration);
opt.SomeSetting
Example: https://github.com/aspnet/Options/blob/dev/test/Microsoft.Framework.OptionsModel.Test/OptionsTest.cs#L80
You can simply access the value of config property Environment
by using Configuration
class like this anywhere in your application.
var environment = Configuration["AppSettings:Environment"];
But if you want it to access through a property of class you can do this
public class AppSettings
{
public string Environment
{
get
{
return new Configuration().Get("AppSettings:Environment").ToString();
}
set;
}
}
Note I haven't set the value of Environment
in setter because this value will be in config.json
so there is no need to set this value in setter.
For more details have a look at this article.