c# - 为什么 DatabaseInitializer 会被调用两次?
问题描述
我继承了一个 MVC,该 MVC 当前使用 ApplicationStart 方法进行了一些设置工作,因此当应用程序通过 IIS 应用程序池恢复运行时,此设置已经执行。
作为伪代码:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
// Build Api autofac container
// Build MVC autofac container
// Resolve serviceOne from the MVC container
var serviceOne = (IServiceOne)DependencyResolver.Current.GetService(typeof(IServiceOne));
// Make setup call - includes external http calls and DbContext checking
serviceOne.syncToExternal();
// Resolve serviceTwo again from the MVC container
var serviceTwo = (IServiceTwo)DependencyResolver.Current.GetService(typeof(IServiceTwo));
// Make setup call - publishes application information to internal message queues so that we know it's running
serviceTwo.syncToInternalSystems();
}
}
在 ApplicationStart 中,我运行了设置 Autofac 容器的正常过程;一个用于 MVC,一个用于 WebApi。在这里注册了各自的 MVC 或 Api 控制器、服务类和我的 DbContext。
ApplicationStart 中的设置工作需要我从 MvcContainer 解析的服务和 DbContext,因为此时无法访问 WebApi。
ServiceOne
从外部 url 检索数据并使用它来播种/检查数据库的当前内容。
ServiceTwo
读取其中的一些数据并将其发布到公司内部的消息队列中。
一旦Application_Start()
完成并且主页已经加载:如果我发出一个通过 MVC 路由的请求,那么 DbCobntext 注册的 databaseInitialzer 不会被调用,因为它在 Application_Start 期间运行,但如果我发出/api
请求,databaseInitializer 确实会被调用。
我怀疑在 ApplicationStart 方法中运行设置会阻止在管理连接的 System.Data.Entity.Database 中设置标志;因此,当从 Api 容器解析 DbContext 时,它认为数据库尚未初始化......?
任何帮助将非常感激。
我的后备方案是将所有设置转移到一个种子方法中,该方法在调用 databaseInitialiser/Migration 时运行;但是了解为什么原始版本的代码未能按预期执行会很有用。
解决方案
无论如何,ApplicationPool 每次启动时都会运行 ApplicationStart。您必须使用另一种机制来填充您的数据库。像迁移一样。
推荐阅读
- java - 如何仅映射 HashMap 的值 - Hibernate
- c# - C#,甚至需要通过引用传递对象吗?
- python - 将大字符串转换为数据框
- complex-event-processing - 使用 esper cep 删除以前的事件
- python - Python:在for循环意外结果中追加列表
- ruby-on-rails - 尝试将数据库从 Heroku 拉到本地时出现带有 Rails 5.2 的 Heroku 错误(pg:pull)
- git - Git:基础变基(Java)
- electron.net - 无法获得桌面类型的窗口
- typescript - 使用 grpc-web 为 vue 配置 Envoy
- imagemagick - ImageMagick,在转换运算符链中设置相对大小