title: Injecting DbContext into service layer
body: <p>How am I supposed to inject my <code>MyDbContext</code> into my database service layer <code>MyService</code>?</p>
  
  <p><strong>Startup.cs</strong></p>
  
  <pre><code>public void ConfigureServices(IServiceCollection services)
  {
      services.AddDbContext&lt;MyDbContext&gt;(options =&gt;
      options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));
      services.AddMvc();
  }
  </code></pre>
  
  <p><strong>MyDbContext.cs</strong></p>
  
  <pre><code>public partial class MyDbContext : DbContext
  {
      public virtual DbSet&lt;User&gt; User { get; set; }
  
      public MyDbContext(DbContextOptions&lt;MyDbContext&gt; options)
      :base(options)
      {
      }
  }
  </code></pre>
  
  <p><strong>appsettings.json</strong></p>
  
  <pre><code>{
    "Logging": {
      "IncludeScopes": false,
      "LogLevel": {
        "Default": "Debug",
        "System": "Information",
        "Microsoft": "Information"
      }
    },
    "ConnectionStrings": {
      "DefaultConnection": "Server=MyServer;Database=MyDatabase;user id=MyUser;password=MyPassword;"
    }
  }
  </code></pre>
  
  <p><strong>MyService.cs</strong></p>
  
  <pre><code>public class MyService
  {
      public User GetUser(string username)
      {
          // Should i remove this call and get the reference from the injection somehow?
          MyDbContext db_context = new MyDbContext(optionsBuilder.Options);
          using (db_context)
          {
              var users = from u in db_context.User where u.WindowsLogin == username select u;
              if (users.Count() == 1)
              {
                  return users.First();
              }
              return null;
          }
      }
  }
  </code></pre>
  
  <p>In my <code>GetUser</code> method, I know I am supposed to be using my injected <code>MyDbContext</code> here but I am not quite sure how to fetch it. Which piece of the puzzle am I missing?</p>