title: How to access DbContext in/from Program class?
body: <p>I have setup an ASP.NET Core project, and configured the <code>DbContext</code> in Startup.cs like -</p>
  <pre class="lang-cs prettyprint-override"><code>public void ConfigureServices(IServiceCollection services)
  {
      services.AddDbContext&lt;DBContext&gt;(options =&gt;
          options.UseSqlServer(Configuration[&quot;ConnectionStrings:DefaultConnection&quot;]));
  }
  </code></pre>
  <p>I can access the <code>DbContext</code> object in controller classes with dependency injection. But I need a reference of the <code>DbContext</code> in the Program class (in Program.cs file).</p>
  <p>I tried the following approach, but it indicates syntax error -</p>
  <pre class="lang-cs prettyprint-override"><code>public class Program
  {
      public static void Main(string[] args)
      {
          using (var db = new DBContext())    // getting syntax error here
          {
              db.Database.EnsureCreated();
          }
          CreateHostBuilder(args).Build().Run();
      }
  
  
      public static IHostBuilder CreateHostBuilder(string[] args) =&gt;
          Host.CreateDefaultBuilder(args)
              .ConfigureWebHostDefaults(webBuilder =&gt;
              {
                  webBuilder.UseStartup&lt;Startup&gt;()
                      .UseUrls(&quot;http://localhost:4000&quot;);
              });
  }
  </code></pre>
  <p>So, how to get access to the <code>DbContext</code> object in the Program class?</p>