Creating a new DbContext

From an existing one in .NET Core

Ikechi Michael
1 min readOct 4, 2019

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.

--

--

Ikechi Michael

I’ve learned I don’t know anything. I've also learned that people will pay for what I know. Maybe that's why they never pay.