title: How to access the DbContext fom asp.net core service
body: <p>I'm a bit stuck in the usage of ASP.NET core and entity framework and all it's (other) components. 
  I'm working on a simple web-app where you can enter some data and have it calculate some statistics (basically strava ultra-light).</p>
  
  <p>So If I open the default blazor app from Visual Studio (2019) I get something like this as Startup</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Threading.Tasks;
  using Microsoft.AspNetCore.Builder;
  using Microsoft.AspNetCore.Components;
  using Microsoft.AspNetCore.Components.Authorization;
  using Microsoft.AspNetCore.Identity;
  using Microsoft.AspNetCore.Identity.UI;
  using Microsoft.AspNetCore.Hosting;
  using Microsoft.AspNetCore.HttpsPolicy;
  using Microsoft.EntityFrameworkCore;
  using Microsoft.Extensions.Configuration;
  using Microsoft.Extensions.DependencyInjection;
  using Microsoft.Extensions.Hosting;
  using BlazorApp1.Areas.Identity;
  using BlazorApp1.Data;
  
  namespace BlazorApp1
  {
      public class Startup
      {
          public Startup(IConfiguration configuration)
          {
              Configuration = configuration;
          }
  
          public IConfiguration Configuration { get; }
  
          // This method gets called by the runtime. Use this method to add services to the container.
          // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
          public void ConfigureServices(IServiceCollection services)
          {
              services.AddDbContext&lt;ApplicationDbContext&gt;(options =&gt;
                  options.UseSqlServer(
                      Configuration.GetConnectionString("DefaultConnection")));
              services.AddDefaultIdentity&lt;IdentityUser&gt;(options =&gt; options.SignIn.RequireConfirmedAccount = true)
                  .AddEntityFrameworkStores&lt;ApplicationDbContext&gt;();
              services.AddRazorPages();
              services.AddServerSideBlazor();
              services.AddScoped&lt;AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider&lt;IdentityUser&gt;&gt;();
              services.AddSingleton&lt;WeatherForecastService&gt;();
          }
  
          // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
          public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
          {
              if (env.IsDevelopment())
              {
                  app.UseDeveloperExceptionPage();
                  app.UseDatabaseErrorPage();
              }
              else
              {
                  app.UseExceptionHandler("/Error");
                  // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                  app.UseHsts();
              }
  
              app.UseHttpsRedirection();
              app.UseStaticFiles();
  
              app.UseRouting();
  
              app.UseAuthentication();
              app.UseAuthorization();
  
              app.UseEndpoints(endpoints =&gt;
              {
                  endpoints.MapControllers();
                  endpoints.MapBlazorHub();
                  endpoints.MapFallbackToPage("/_Host");
              });
          }
      }
  }
  </code></pre>
  
  <p>And something like this as a Service</p>
  
  <pre><code>using System;
  using System.Linq;
  using System.Threading.Tasks;
  
  namespace BlazorApp1.Data
  {
      public class WeatherForecastService
      {
          private static readonly string[] Summaries = new[]
          {
              "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
          };
  
          public Task&lt;WeatherForecast[]&gt; GetForecastAsync(DateTime startDate)
          {
              var rng = new Random();
              return Task.FromResult(Enumerable.Range(1, 5).Select(index =&gt; new WeatherForecast
              {
                  Date = startDate.AddDays(index),
                  TemperatureC = rng.Next(-20, 55),
                  Summary = Summaries[rng.Next(Summaries.Length)]
              }).ToArray());
          }
      }
  }
  </code></pre>
  
  <p>So I added a model for my data</p>
  
  <pre><code>using Microsoft.AspNetCore.Identity;
  using BlazorApp1.Database.Types;
  using System.ComponentModel.DataAnnotations;
  
  namespace BlazorApp1.Database.Entity
  {
      public class Activity
      {
          public string ActivityData { get; set; }
          public ActivityType ActivityType { get; set; }
          public float Distance { get; set; }
  
          [Key]
          public int Id { get; private set; }
  
          public IdentityUser User { get; set; }
      }
  }
  </code></pre>
  
  <p>And added it to the ApplicationDbContext</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Text;
  using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
  using Microsoft.EntityFrameworkCore;
  
  namespace BlazorApp1.Data
  {
      public class ApplicationDbContext : IdentityDbContext
      {
          public ApplicationDbContext(DbContextOptions&lt;ApplicationDbContext&gt; options)
              : base(options)
          {
          }
  
          public DbSet&lt;Activity&gt; Activities { get; set; }
      }
  }
  </code></pre>
  
  <p>So now I want to create my own Service similar to the WeatherForecastService and that is where I get stuck.</p>
  
  <pre><code>using log4net;
  using Microsoft.AspNetCore.Mvc.RazorPages;
  using Microsoft.EntityFrameworkCore;
  using Microsoft.Extensions.DependencyInjection;
  using BlazorApp1.Data.Model;
  using BlazorApp1.Database;
  using System.Collections.Generic;
  using System.Threading.Tasks;
  
  namespace BlazorApp1.Data
  {
      public class LeaderBoardService
      {
          private readonly static ILog _logger = LogManager.GetLogger(typeof(LeaderBoardService));
  
  
          public Task&lt;List&lt;LeaderBoardItem&gt;&gt; GetOverallLeaderboard()
          {
              //I want to access the database context from here.
              return Task.FromResult(result);
          }
      }
  }
  </code></pre>
  
  <p>Also, I need to add this Service to the Startup.ConfigureServices().
  From what I have found so far is that I can use <code>services.AddScoped&lt;LeaderBoardService&gt;()</code>, <code>services.AddSingleton&lt;LeaderBoardService&gt;()</code> and <code>services.AddTransient&lt;LeaderBoardService&gt;()</code> to accomplish this and it seems like <code>services.AddScoped&lt;LeaderBoardService&gt;()</code> is the best to use.</p>
  
  <p>It could be just me that has this problem, but the documentation seems to be missing some hint on how to accomplish this seemingly easy task.</p>
  
  <p>So far I looked at the following sites:</p>
  
  <ol>
  <li><a href="https://docs.microsoft.com/en-us/aspnet/core/data/ef-rp/intro?view=aspnetcore-3.1&amp;tabs=visual-studio" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/aspnet/core/data/ef-rp/intro?view=aspnetcore-3.1&amp;tabs=visual-studio</a> 
  
  <ul>
  <li>but there are no Services used in this example.</li>
  </ul></li>
  <li><a href="https://docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext#using-dbcontext-with-dependency-injection" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext#using-dbcontext-with-dependency-injection</a> 
  
  <ul>
  <li>Although it seems like the solution is just to add the context as a parameter to the constructor of the service I can't seem to find how to add this parameter during any of the calls.</li>
  </ul></li>
  <li><a href="https://stackoverflow.com/a/48698290">https://stackoverflow.com/a/48698290</a>
  
  <ul>
  <li>I'm not 100% sure if this is what I'm looking for but if it turns out to be I would like to have some hint on how to implement this.</li>
  </ul></li>
  <li><a href="https://stackoverflow.com/questions/50073874/asp-net-core-access-dbcontext-within-class">asp.net core access dbcontext within class</a>
  
  <ul>
  <li>Here some middleware is used and I guess that is not what I'm looking for.</li>
  </ul></li>
  <li><a href="https://stackoverflow.com/a/44484724/2986756">https://stackoverflow.com/a/44484724/2986756</a>
  
  <ul>
  <li>This one is an option to make the DbContext Transient, also not what I'm looking for.</li>
  </ul></li>
  <li><a href="https://stackoverflow.com/a/37511175">https://stackoverflow.com/a/37511175</a>
  
  <ul>
  <li>Here the database is placed in a Singleton. Although I could use this I don't think I should.</li>
  </ul></li>
  </ol>