What is the correct/recommended way of accessing the config.json
file (or wherever else config is stored) in ASP.NET vNext?
In the Startup
clas
In the first place, you should avoid registering your database context as a singleton. Also passing around the raw IConfiguration
interface isn't a good practice.
In stead could create a POCO options class:
public class DbOptions
{
public string ConnectionString { get; set }
}
And populate it in the ConfigureServices
method using the section in the config.json:
services.Configure(Configuration.GetConfigurationSection("Data:DefaultConnection"));
Then you can inject it into your DbContext
(and in controllers, etc.):
public sealed class Context : IdentityDbContext
{
private readonly DbOptions _options;
public DbSet Clients { get; set; }
public Context(IOptions optionsAccessor)
{
// store the injected options
_options = optionsAccessor.Options;
}
// other code..
}