Reputation: 6015
I'm using ASP.NET Core 2 I'm trying to access Configuration in context class,I've done configurations like this: in Program.cs:
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
......
.ConfigureAppConfiguration((builderContext, config) =>
{
IHostingEnvironment env = builderContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
})
.Build();
in Startup.cs:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
I can access it in controllers like this:
public HomeController(IConfiguration configuration)
{...}
but how do I access it in context class? thanks
Upvotes: 8
Views: 12057
Reputation: 58733
In your situation where you need IConfiguration in a DbContext class, you will have to add it to the constructor:
public class MyDbContext : DbContext
{
private readonly IConfiguration _configuration;
public MyDbContext(IConfiguration configuration)
{
_configuration = configuration;
}
}
But you also have to get MyDbContext
from DI then. So a static class cannot receive it as a parameter. You will have to re-think how you are using the DbContext, and change it so that you get the context somewhere with access to DI, and pass that as an argument to any static methods that require it.
Upvotes: 13