Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DbContext.OnConfiguring not getting called and behaving weird in Asp.net core

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. OnConfiguring method .

Instance created but OnConfiguring not called yet Instance created

.

OnConfiguring called on looking into the object but it's breakpoint didn't hit. OnConfiguring called

like image 554
Hassaan Akbar Avatar asked Mar 12 '23 09:03

Hassaan Akbar


2 Answers

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.

like image 198
Gert Arnold Avatar answered Mar 25 '23 16:03

Gert Arnold


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"));
}
like image 35
dml Avatar answered Mar 25 '23 17:03

dml