Home > Net >  Extract EF Core DbContextOptions from DbContext
Extract EF Core DbContextOptions from DbContext

Time:12-13

After a DbContext is created, is it possible to extract the DbContextOptions that was used to create it?

(Perhaps by using something similar to RelationalOptionsExtension.Extract(), an EF infrastructure service, etc.)

CodePudding user response:

No official (public) way. But you can use two (internal) infrastructure methods to obtain it.

First is the GetService<TService> extension method located in AccessorExtensions class, which then can be used to obtain the IDbContextServices service instance - undocumented, but one of its members is

IDbContextOptions ContextOptions { get; }

which is exactly what you need.

So the code is like this:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Internal;

DbContext dbContext;
var dbOptions = db.GetService<IDbContextServices>().ContextOptions;

Note that the return type is interface, but it can be cast to DbContextOptions if needed.

CodePudding user response:

OnConfiguring is run for each DbContext instance so you can override it to examine and modify DbContextOptionsBuilder passed in.

CodePudding user response:

What I use is a factory method that can return either a DbContext or a DbContextOptions object. Afterwards I use that either in DI (Autofac) or for unitests (usually an in-memory db).

If this isn't an option you could probably use Reflection and create an extension method to return the private field private readonly DbContextOptions _options; from the DbContext object. This is kind of a hack and workaround, if you control the instantiation of the DbContext I would use option one.

  • Related