title: Why does Scoped service resolve as two different instances for same request?
body: <p>I have a simple service that contains a <code>List&lt;Foo&gt;</code>.  In Startup.cs, I am using the <code>services.addScoped&lt;Foo, Foo&gt;()</code> method.</p>
  
  <p>I am inject the service instance in two different places (controller and middleware), and for a single request, I would expect to get the same instance.  However, this does not appear to be happening.</p>
  
  <p>Even though I am adding a Foo to the List in the Controller Action, the Foo list in the Middleware is always empty.  Why is this?</p>
  
  <p>I have tried changing the service registration to a singleton, using <code>AddSingleton()</code> and it works as expected.  However, this has to be scoped to the current request.  Any help or ideas are greatly appreciated!</p>
  
  <p><strong>FooService.cs</strong></p>
  
  <pre><code>public class FooService
  {
      public List&lt;Foo&gt; Foos = new List&lt;Foo&gt;();
  }
  </code></pre>
  
  <p><strong>Startup.cs</strong></p>
  
  <pre><code>...
  public void ConfigureServices(IServiceCollection services)
  {
      ...
      services.AddScoped&lt;FooService, FooService&gt;();
  }
  </code></pre>
  
  <p><strong>[Below are the two places where I am injecting the service, resulting in two different instances]</strong></p>
  
  <p><strong>MyController.cs</strong></p>
  
  <pre><code>public class MyController : Controller
  {
      public MyController(FooService fooService)
      {
          this.fooService = fooService;
      }
  
      [HttpPost]
      public void TestAddFoo()
      {
          //add foo to List
          this.fooService.Foos.Add(new Foo());
      }
  }
  </code></pre>
  
  <p><strong>FooMiddleware.cs</strong></p>
  
  <pre><code>public AppMessageMiddleware(RequestDelegate next, IServiceProvider serviceProvider)
  {
      this.next = next;
      this.serviceProvider = serviceProvider;
  }
  
  public async Task Invoke(HttpContext context)
  {
      context.Response.OnStarting(() =&gt;
      {
          var fooService = this.serviceProvider.GetService(typeof(FooService)) as FooService;
  
          var fooCount = fooService.Foos.Count; // always equals zero
  
          return Task.CompletedTask;
      });
  
      await this.next(context);
  
  }
  </code></pre>