首页 > 解决方案 > 为什么 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 时运行;但是了解为什么原始版本的代码未能按预期执行会很有用。

标签: c#entity-frameworkautofac

解决方案


无论如何,ApplicationPool 每次启动时都会运行 ApplicationStart。您必须使用另一种机制来填充您的数据库。像迁移一样。


推荐阅读