Blog
Add a custom configuration file using options and configuration objects
It can be useful to have multiple configuration files, and it follows some development best practices like the Interface Segregation Principle or the Separation of Concerns. Moreover, it allows you to have the behavior you want on each configuration file.
It's very simple and easy to do this using options and configuration objects.
The first step is to add a file to your project, here customSettings.json, with the following content:
{
"CustomSection1": {
"Hi": "Hi!",
"Hello": "Hello!"
},
"CustomSection2": {
"Bye": "Bye!"
}
}
Create the model of the configuration settings you want to add:
namespace WebApplication1.Models.CustomSettings
{
public class CustomSection1
{
public string Hi { get; set; }
public string Hello { get; set; }
}
public class CustomSection2
{
public string Bye { get; set; }
}
}
Then, use the configuration provider you want (the JSON one here), add your class to the service container and bind it to the configuration:
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddJsonFile($"customSettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
if (env.IsDevelopment())
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.Configure<CustomSection1>(options => Configuration.GetSection("CustomSection1").Bind(options));
services.Configure<CustomSection2>(options => Configuration.GetSection("CustomSection2").Bind(options));
services.AddMvc();
}
The work is done! You can now access your settings from your controllers using Dependency Injection on IOptions
public class HomeController : Controller
{
private readonly CustomSection1 _customSection1;
private readonly CustomSection2 _customSection2;
public HomeController(
IOptions<CustomSection1> customSection1
, IOptions<CustomSection2> customSection2)
{
_customSection1 = customSection1.Value;
_customSection2 = customSection2.Value;
}
December 27, 2016