问题描述
在我的asp.net核心项目中,我有一个从DbContext派生的ReadingContext类.根据文档,应为创建的每个DbContext实例调用OnConfiguring.
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.
但是在我的情况下,仅当我在调试时检查实例时才调用它.我在OnConfiguring中有一个断点,但是即使调用该方法也没有命中它.
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方法.
OnConfiguring method..
实例,但尚未调用OnConfiguring
.
OnConfiguring调用了该对象,但没有遇到断点.
OnConfiguring called on looking into the object but it's breakpoint didn't hit.
推荐答案
我不知道您指的是哪个文档,但是我确定它并没有说在创建上下文时运行 .因为没有.每当第一次实际使用上下文实例时,它就会运行.这就是为什么在调试视图中开始检查上下文后立即看到方法调用的原因.当您在调试器中的断点上暂停时,即使代码被命中,调试器也永远不会跳到另一个断点.
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.
这篇关于DbContext.OnConfiguring没有被调用并且在Asp.net核心中表现怪异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!