title: DBContext Not Resolving When Controller Created (.NET5, ASPCore, EF)
body: <p><strong><a href="https://github.com/AlexMercedCoder/PracticeDotNet5Project" rel="nofollow noreferrer">Here is the Link to the Repository With My Code</a></strong></p>
  <p>Beyond fixing the error, I'm glad to take any tips on improving my code, this is my first .NET5 Project for me to practice. I read a lot of docs trying to resolve this error and most of the stack overflow entries are people forgetting to register their service which based on the code below I'm pretty Sure I did.</p>
  <h2>The Error</h2>
  <p>The Code Runs Fine but when I make a request to my PersonController I get the following error:</p>
  <pre><code>fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
        An unhandled exception has occurred while executing the request.
        System.InvalidOperationException: Unable to resolve service for type 'firstapi.Models.PersonContext' while attempting to activate 'firstapi.Controllers.PersonController'.
           at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
           at lambda_method3(Closure , IServiceProvider , Object[] )
           at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.&lt;&gt;c__DisplayClass4_0.&lt;CreateActivator&gt;b__0(ControllerContext controllerContext)
           at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.&lt;&gt;c__DisplayClass5_0.&lt;CreateControllerFactory&gt;g__CreateController|0(ControllerContext controllerContext)
           at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State&amp; next, Scope&amp; scope, Object&amp; state, Boolean&amp; isCompleted)
           at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
        --- End of stack trace from previous location ---
           at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.&lt;InvokeFilterPipelineAsync&gt;g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
           at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.&lt;InvokeAsync&gt;g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
           at Microsoft.AspNetCore.Routing.EndpointMiddleware.&lt;Invoke&gt;g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
           at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
           at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
           at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
           at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
  </code></pre>
  <h2>My Model</h2>
  <pre class="lang-cs prettyprint-override"><code>namespace firstapi.Models
  {
      public class Person
      {
          public long Id { get; set; }
          public string Name { get; set; }
          public int age { get; set; }
      }
  }
  </code></pre>
  <h2>My Context</h2>
  <pre class="lang-cs prettyprint-override"><code>using Microsoft.EntityFrameworkCore;
  
  namespace firstapi.Models
  {
      public class PersonContext:DbContext
      {
          public PersonContext(DbContextOptions&lt;PersonContext&gt; options) : base(options)
          {
          }
          public DbSet&lt;Person&gt; Persons { get; set; }
      }
  }
  </code></pre>
  <h2>My Startup.cs</h2>
  <pre class="lang-cs prettyprint-override"><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Threading.Tasks;
  using Microsoft.AspNetCore.Builder;
  using Microsoft.AspNetCore.Hosting;
  using Microsoft.AspNetCore.HttpsPolicy;
  using Microsoft.AspNetCore.Mvc;
  using Microsoft.Extensions.Configuration;
  using Microsoft.Extensions.DependencyInjection;
  using Microsoft.Extensions.Hosting;
  using Microsoft.Extensions.Logging;
  using Microsoft.OpenApi.Models;
  using firstapi.Models;
  using Microsoft.EntityFrameworkCore;
  
  namespace firstapi
  {
      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.
          public void ConfigureServices(IServiceCollection services)
          {
  
              services.AddControllers();
              services.AddSwaggerGen(c =&gt;
              {
                  c.SwaggerDoc(&quot;v1&quot;, new OpenApiInfo { Title = &quot;firstapi&quot;, Version = &quot;v1&quot; });
  
                  services.AddMvc();
  
                  // Setup our datanase connection string and add our database connection
                  var connectionString = Configuration[&quot;DbContextSettings:ConnectionString&quot;];
                  Console.WriteLine(connectionString);
                  services.AddDbContext&lt;PersonContext&gt;(opt =&gt; opt.UseNpgsql(connectionString));
              });
          }
  
          // 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.UseSwagger();
                  app.UseSwaggerUI(c =&gt; c.SwaggerEndpoint(&quot;/swagger/v1/swagger.json&quot;, &quot;firstapi v1&quot;));
              }
  
              app.UseHttpsRedirection();
  
              app.UseRouting();
  
              app.UseAuthorization();
  
              app.UseEndpoints(endpoints =&gt;
              {
                  endpoints.MapControllerRoute(
                  name: &quot;default&quot;,
                  pattern: &quot;{controller=Home}/{action=Index}/{id?}&quot;);
              });
          }
      }
  }
  </code></pre>
  <h2>My Controller</h2>
  <pre class="lang-cs prettyprint-override"><code>using firstapi.Models;
  using System.Collections.Generic;
  using Microsoft.AspNetCore.Http;
  using Microsoft.AspNetCore.Mvc;
  using System.Linq;
  
  namespace firstapi.Controllers
  {
     public class PersonController
      {
          private readonly PersonContext People;
  
          public PersonController(PersonContext people){
              People = people;
          }
  
          public IEnumerable&lt;Person&gt; index(){
              return People.Persons.ToList();
          }
  
          public IEnumerable&lt;Person&gt; Post([FromBody]Person person){
              People.Persons.Add(person);
              People.SaveChanges();
              return People.Persons.ToList();
          }
  
      }
  }
  </code></pre>
  <h2>My appsettings.json</h2>
  <pre class="lang-json prettyprint-override"><code>{
    &quot;Logging&quot;: {
      &quot;LogLevel&quot;: {
        &quot;Default&quot;: &quot;Information&quot;,
        &quot;Microsoft&quot;: &quot;Warning&quot;,
        &quot;Microsoft.Hosting.Lifetime&quot;: &quot;Information&quot;
      }
    },
    &quot;AllowedHosts&quot;: &quot;*&quot;,
    &quot;DBContextSettings&quot;: {
      &quot;ConnectionString&quot;: &quot;User ID=test5;Password=test5;Host=localhost;Port=5432;Database=firstdotnet;Pooling=true;&quot;
    }
  }
  </code></pre>
  <h2>csproj</h2>
  <pre class="lang-xml prettyprint-override"><code>&lt;Project Sdk=&quot;Microsoft.NET.Sdk.Web&quot;&gt;
  
    &lt;PropertyGroup&gt;
      &lt;TargetFramework&gt;net5.0&lt;/TargetFramework&gt;
      &lt;GenerateRuntimeConfigurationFiles&gt;True&lt;/GenerateRuntimeConfigurationFiles&gt;
    &lt;/PropertyGroup&gt;
  
    &lt;ItemGroup&gt;
      &lt;PackageReference Include=&quot;EntityFramework&quot; Version=&quot;6.4.4&quot; /&gt;
      &lt;PackageReference Include=&quot;Microsoft.AspNetCore.Http.Features&quot; Version=&quot;5.0.4&quot; /&gt;
      &lt;PackageReference Include=&quot;Microsoft.AspNetCore.Mvc.Core&quot; Version=&quot;2.2.5&quot; /&gt;
      &lt;PackageReference Include=&quot;Npgsql.EntityFrameworkCore.PostgreSQL&quot; Version=&quot;5.0.2&quot; /&gt;
      &lt;PackageReference Include=&quot;Swashbuckle.AspNetCore&quot; Version=&quot;5.6.3&quot; /&gt;
    &lt;/ItemGroup&gt;
  
  &lt;/Project&gt;
  </code></pre>