Why does the DatabaseInitializer get called twice?

核能气质少年 提交于 2019-12-02 18:50:19

问题


I’ve inherited an MVC that currently does some setup work with the ApplicationStart method so that when the application comes back to life with an IIS Application pool this setup has already been carried out.

As pseudo-code:

    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();
      }
    }

In the ApplicationStart I run through the normal process of setting up Autofac containers; one for the MVC and one for the WebApi. In here the respective MVC or Api controllers, service classes and my DbContext are registered.

The setup work in the ApplicationStart needs a service and a DbContext which I resolve from the MvcContainer, as the WebApi one is not accessible at this point.

ServiceOne retrieves data from an external url and using this to seed / check the current contents of the database.

ServiceTwo reads back some of this data and publishes it to internal message queues within the company.

Once the Application_Start() has finished and the Home page has loaded: if I make a request which routes through the MVC then the DbCobntext's registered databaseInitialzer does not get called as it was run during the Application_Start, but if I make an /api request the databaseInitializer does get called.

I suspect that running the setup in ApplicationStart method is preventing a flag being set in the System.Data.Entity.Database which managed the Connection; hence when the DbContext is resolved from the Api Container it thinks the database hasn’t been initialised...?

Any help would be much appreciated.

My fallback will be to shift all of the setup into a seed method which runs when the databaseInitialiser/Migration is called; but it would be useful to know why the original version of the code was failing to execute as expected.


回答1:


the ApplicationStart run every time the ApplicationPool starts, no matter what. You have to use another mechanism to populate your DB. Like Migrations.



来源:https://stackoverflow.com/questions/54137962/why-does-the-databaseinitializer-get-called-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!