In my asp.net core project i have a ReadingContext
class derived from DbContext
. According to documentation OnConfiguring
should be called for every instance of DbContext
that is created.
But in my case it is only called when i inspect the instance while debugging. I have a breakpoint inside OnConfiguring
but it is not hit even when the method is called.
OnConfiguring method. .
Instance created but OnConfiguring
not called yet
.
OnConfiguring called on looking into the object but it's breakpoint didn't hit.
According to documentation OnConfiguring should be called for every instance of DbContext that is created.
I don't know which documentation you refer to, but I'm sure it doesn't say that OnConfiguring
runs when the context is created. Because it doesn't. It runs whenever a context instance is actually used for the first time. That's why you see the method call as soon as you start inspecting the context in the debug view. When you pause on a breakpoint in the debugger, the debugger will never jump to another breakpoint, even when the code is hit.
Contexts are supposed to be created and disposed in large numbers. Therefore, creating a context must be as light-weight as possible. Its internal components are created by lazy initialization as much as possible.
Just in case anyone else had this issue, I had to use an empty constructor to get OnConfiguring called:
public ReadingContext() : base()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder
optionsBuilder)
{
var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json",
optional: true, reloadOnChange: true);
config = builder.Build();
optionsBuilder.UseSqlServer(config.GetConnectionString
("ReadingContextConnection"));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With