title: Create an EF Core DbContext at runtime based on request parameters
body: <p><strong>Background</strong></p>
  
  <p>We are building a web application using ASP.Net Core and Entity Framework Core 2.2</p>
  
  <p>We are connecting to legacy databases. The setup is that there are 16 databases, all with the exact same schema, holding different contextual data. We cannot change this.</p>
  
  <p>We have a requirement to connect to a specific database at runtime, based on request parameters.</p>
  
  <p>Imagine that there is a database for every business under the parent company.</p>
  
  <p>Imagine that each database has tables like Employee, Client and Shift (a shift that the employee has worked for a Client).</p>
  
  <p>There is also a 'central' database which holds information common across all the other databases, like settings etc.</p>
  
  <p>We have a requirement to list all the Employees across all businesses in a single list view.</p>
  
  <p>We plan to retrieve this data by using a SQL View in the central database, which simply does a UNION across each of the other databases (if you have a suggestion on how to do this better, please share it).</p>
  
  <pre><code>CREATE VIEW dbo.v_all_employees AS 
      SELECT EmployeeId, Fullname, 1 AS BusinessId FROM BusinessA.dbo.Employees
      UNION ALL SELECT EmployeeId, Fullname, 2 AS BusinessId FROM BusinessB.dbo.Employees
      -- etc. etc.
  </code></pre>
  
  <p>We have a single set of Models which represent all the Entities (tables) across all the databases, since they share the exact same schema e.g. one Employee class, one Client class etc.</p>
  
  <p><strong>Use case</strong></p>
  
  <p>The user goes to a web page to see the list of Employees across all the businesses via this route:</p>
  
  <p><a href="http://example.org/employees" rel="noreferrer">http://example.org/employees</a> </p>
  
  <p>User then clicks on a 'Details' link for an individual employee to view further details, taking the user to the url:</p>
  
  <p><a href="http://example.org/employees/details?employeeId=123&amp;businessId=xyz" rel="noreferrer">http://example.org/employees/details?employeeId=123&amp;businessId=xyz</a></p>
  
  <p>What I am stuck on is how do we instantiate the business specific DbContext at runtime, given the BusinessId.</p>
  
  <p>I have come up with three ways (and now a fourth thanks to @mylee) to achieve the desired result and am looking for feedback from the community.</p>
  
  <p>Every option assumes that each DbContext will implement an interface which exposes all the DbSets and DbContext methods and then we'll use the Factory pattern to handle the determination of which DbContext implementation to use.</p>
  
  <p><strong><em>The first option:</em></strong>
  Simply have the Factory create the correct DbContext based on the request parameter 'bizId'. </p>
  
  <p>However, this requires that each DbContext over-rides the OnConfiguring method and sets up the DbProvider - something that the dotnet Core framework does for us via its IoC container extension method <a href="https://docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext#using-dbcontext-with-dependency-injection" rel="noreferrer">AddDbContext</a>:</p>
  
  <pre><code>public class ContextFactory : IContextFactory
  {
      public IBIZContext GetContext(int bizId)
      {
          switch (bizId)
          {
              // Newing-up the DbContexts like this requires that the OnConfiguring method
              // for each context be present in each DbContext to setup the DbProvider
              // with the correct connection string.
              case 6:
                  return new BIZ_AContext();
              case 7:
                  return new BIZ_BContext();
              default:
                  throw new Exception("Unexpected Business Id");
          }
      }
  }
  </code></pre>
  
  <p>This issue with this is that I don't like how we're newing up the contexts here. It requires that we over-ride the OnConfiguring method in each context and have access to the Connection String. </p>
  
  <p><strong><em>The second option:</em></strong></p>
  
  <p>I would prefer to use the built in IoC Container which is setup in Startup.cs but this exhibits the Service Locator Anti-Pattern.
  Also, it leaks the HttpContext out of the Web project into the Infrastructure project (I'm using an Onion architecture):</p>
  
  <pre><code>public class ContextFactoryUsingLocator : IContextFactoryUsingLocator
  {
      public IBIZContext GetContext(IHttpContextAccessor httpContextFactory, int bizId)
      {
          // Injecting the HttpContextAccessor gives us access to the IoC Container via RequestServices;
          // But using it here exhibits the Service Locator anti-pattern.
          // Perhaps its ok to use the Service Locator pattern within a Factory in this case?
          switch (bizId)
          {
              case 6:
                  return (BIZ_AContext)httpContextFactory.HttpContext.RequestServices.GetService(typeof(BIZ_AContext));
              case 7:
                  return (BIZ_BContext)httpContextFactory.HttpContext.RequestServices.GetService(typeof(BIZ_BContext));
              default:
                  throw new Exception("Unexpected Business Id");
          }
      }
  }
  </code></pre>
  
  <p><strong><em>A third option</em></strong></p>
  
  <p>Inject each DbContext into the Factory and have the Factory simply return the correct instance:</p>
  
  <pre><code>public class ContextFactoryInjected : IContextFactoryInjected
  {
      private readonly BIZ_AContext _bizAContext;
      private readonly BIZ_BContext _bizBContext;
  
      public ContextFactoryInjected(
          BIZ_AContext bizAContext, 
          // 14 other DbContext dependencies omitted here for brevity
          BIZ_BContext bizBContext)
      {
          // Injecting all 16 DbContexts into the Factory seems to counter the intention of the Factory since the IoC Container
          // would be managing the creation of all the instances; isn't that the responsibility of the Factory?
  
          // More importantly; wouldn't this have serious performance implications, creating 16 instances of a DbContext on every Request?
          _bizAContext = bizAContext;
          _bizBContext = bizBContext;
      }
  
      public IBIZContext GetContext(int bizId)
      {
          switch (bizId)
          {
              case 6:
                  return _bizAContext;
              case 7:
                  return _bizBContext;
              default:
                  throw new Exception("Unexpected Business Id");
          }
      }
  }
  </code></pre>
  
  <p><strong><em>The fourth option</em></strong>
  Encapsulate the configuration of the DbContext within the Factory (this method was suggested by @mylee)</p>
  
  <pre><code>public class ContextFactoryConfigured : IContextFactoryConfigured
  {
      public IBIZContext GetContext(int bizId)
      {
          switch (bizId)
          {
              // Newing-up the DbContexts like this encapsulates all the details required for the DbContext within the Factory
              case 6:
                  var bizAOptionsBuilder = new DbContextOptionsBuilder&lt;BizAContext&gt;();
                  bizAOptionsBuilder.UseSqlServer(Settings.BizAConnectionString);
                  return new BizAContext(bizAOptionsBuilder.Options);
              case 7:
                  var bizBOptionsBuilder = new DbContextOptionsBuilder&lt;BizBContext&gt;();
                  bizBOptionsBuilder.UseSqlServer(Settings.BizBConnectionString);
                  return new BizBContext(bizBOptionsBuilder.Options);
              default:
                  throw new Exception("Unexpected Business Id");
          }
      }
  }
  </code></pre>
  
  <p>Do you agree that option 2 exhibits the Service Locator anti-pattern i.e. is it right to say that the Factory depends on the objects its managing the creation of?</p>
  
  <p>Do you think that option 4 is the best approach out of these, given that it is normally the responsibility of a Factory to 'new-up' its objects AND it doesn't result in a mixing of concerns (i.e. doesn't require the HttpContext ) AND it encapsulates all the details (e.g. ConnectionString) required to build the context within the Factory?</p>
  
  <p>Or is there a way to achieve this using Dependency Injection without resulting in a mixing of concerns?</p>
  
  <p>Or is there an even better way that I've not mentioned here?</p>