My application is an ASP.NET Core 1.0 Web API. I am using Entity framework.
I wan't to change the CommandTimeout like this:
public class MyDbContext: DbContext
{
private const int Timeout = 180;
public MyDbContext(DbContextOptions options): base(options)
{
this.Database.SetCommandTimeout(Timeout);
}
}
this works if Timeout is defined in my class.
However, I would like to have the value of my Timeout inside my appsettings.json file like this:
"DbContextSettings": {
"Timeout": "180"
}
so there are two ways to set the CommandTimeout now:
- Pass the
CommandTimeOutInSecondsas a parameter to the constructor. - Get the value out of
appsettings.jsoninside the constructor of my class
I don't know how to achieve one of the ways.
Is this possible? or is there any known workaround?
Edit
Iam never really Initailizing MyDbContext. I do this in ConfigureServices in the Startup class like this:
services.AddDbContext<MyDbContext>(db => db.UseSqlServer("secret"));
Edit 2
@dennisanberlin so let's say I have a controller calling the following method:
public class SomeRepository
{
private MyDbContext context;
public SomeRepository(MyDbContext myContext)
{
this.context = myContext;
}
public Person SomeMethodCalledByController(){
return myContext.SomeTableWhichContainsPersons.FirstOrDefault(person => person.name == "Bob");
}
}
The class SomeRepository is never getting initialized by me. Iam doing this via dependency injection in the startup like this:
services.AddTransient<SomeRepository>();
The class knows about MyDbContext from the above shown line:
services.AddDbContext<MyDbContext>(db => db.UseSqlServer("secret"));
Therefore I never pass an object of MyDbContext directly to any of my classes working with the database.