title: Where should I put Database.EnsureCreated?
body: <p>I have an Entity Framework Core + ASP.NET Core application and when my application starts up I want to ensure that the database is created, and eventually (once I have migrations) I want to ensure that those are also run.</p>
  
  <p>Initially I put <code>Database.EnsureCreated()</code> into the constructor of my <code>DbContext</code> but that appears to run every time someone hits my application since a new instance of the <code>DbContext</code> is created each time.</p>
  
  <p>I tried to put it into my startup code, but I need an instance of my <code>DbContext</code> to do that and it is unclear how exactly to get one.  I am configuring EF as so:</p>
  
  <pre><code>serviceCollection.AddEntityFramework()
      .AddSqlServer()
      .AddDbContext&lt;Models.MyContext&gt;(options =&gt; options.UseSqlServer(...));
  </code></pre>
  
  <p>I don't see a way to get an instance of the DbContext from the service collection, and I don't see any appropriate singleton to inject a DbContext into so I can do some one-time initialization.</p>
  
  <p>So what is the best place to ensure some code related to my DbContext is called once per application run?</p>