title: How to replace IDbContextFactory in Service Injection for xUnit integration test
body: <p>I am setting up an API using .NET 5 with dependency injection for my data access; using Entity Framework code first. I need to use IDbContextFactory because some of my controllers need to use more than one DbContext instance for proper Unit of Work scope.</p>
  <p>I'm also trying to use xUnit for integration tests and am running into difficulties getting it to use in memory database.</p>
  <p>Here is the relevant snippet from my Startup class</p>
  <pre><code>        public void ConfigureServices(IServiceCollection services)
          {
              services.AddDbContextFactory&lt;ApplicationDbContext&gt;(
                  options =&gt; options.UseSqlServer(&quot;connection string&quot;)
              );
  
              //other services configured
          }
  </code></pre>
  <p>And this is the xUnit Application Factory that is supposed to remove the existing DbContextFactory and replace it with the InMemory factory.</p>
  <pre><code>public class TestApplicationFactory&lt;TStartup&gt;
          : WebApplicationFactory&lt;TStartup&gt; where TStartup: class
      {
          protected override void ConfigureWebHost(IWebHostBuilder builder)
          {
              builder.ConfigureServices(services =&gt;
              {
                  var contextFactory = services.SingleOrDefault(
                      d =&gt; d.ServiceType ==
                          typeof(IDbContextFactory&lt;ApplicationDbContext&gt;)
                  );
                  services.Remove(contextFactory);
                  
                  services.AddDbContextFactory&lt;ApplicationDbContext&gt;(
                      options =&gt; options.UseInMemoryDatabase(&quot;InMemoryDbForTesting&quot;)
                  );
  
                  var sp = services.BuildServiceProvider();
                  var dbf = sp.GetRequiredService&lt;IDbContextFactory&lt;ApplicationDbContext&gt;&gt;();
                  var db = dbf.CreateDbContext();
                  db.Database.EnsureCreated();
  
                  // Pass the context to a class that will add seed data
                  DbSeed.InitializeDbForTests(db);
              });
          }
  </code></pre>
  <p>When I step through in debug, it appears to be removing the existing factory as evidenced by the count of services dropping after the services.Remove(contextFactory); line and it also seems to add the new one, again by looking at the count.</p>
  <p>This is not throwing any errors, it's just not using the new DbContextFactory.</p>
  <p>What am I missing here?</p>
  <p>Thank you in advance for any help.</p>