mykeels.com

Creating a new DbContext

From an existing one in .NET Core

Creating a new DbContext

From an existing one in .NET Core

Like me, you might have injected a DBContext into your web app’s service provider with Startup.cs, and now need to create a new instance of it on the fly, because multi-threading.

Or you just need to create a new instance manually, for whatever reason.

await foreach (var image in query)
{
  using (var _newContext = new MyDbContext(_context.Options))
  {
    ...
  }
}

Where _context is a MyDbContext instance, injected into my constructor by the service provider.

Tweaking the MyDbContext class

You might have noticed I passed _context.Options as an argument into MyDbContext's constructor.

That’s because MyDbContext has the following constructor definition:

public MyDbContext(DbContextOptions<MyDbContext> options): base(options)

However, once created, an instance has no way to give back the options it was created with.

We can fix that by adding a readonly property Options:

Now, by passing Options as a parameter, we can create another MyDbContext instance, anytime we like.

Tags