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.

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.

Image for post
Image for post

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.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store