Moritz Schmidt
Moritz Schmidt

Reputation: 2823

Pass parameter to class which inherits from DbContext

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:

  1. Pass the CommandTimeOutInSeconds as a parameter to the constructor.
  2. Get the value out of appsettings.json inside 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.

Upvotes: 1

Views: 3881

Answers (1)

Dennis Larisch
Dennis Larisch

Reputation: 573

You can pass the timeout to your constructor like this:

public MyDbContext(DbContextOptions options, int timeout): base(options)
   {
       Timeout = timeout;
       this.Database.SetCommandTimeout(Timeout);
   }

And here is an example on how to read settings from your App settings.json csharpcorner

EDIT

public MyDbContext(DbContextOptions options): base(options)
   {
       int timeout = //return timeout setting from appsettings.json
       this.Database.SetCommandTimeout(Timeout);
   }

You can try to do it that way, that you read your appsettings.json inside your constructor.

Upvotes: 2

Related Questions