0

Is it possible to add more than 1 DbContextFactory, for the same DbContext, to the services collection in an ASP.NET Core application?

For example, I am trying the following code ...

services
  .AddDbContextFactory<WibWorkspaceContext, WibWorkspaceContextFactory>();

services
  .AddDbContextFactory<WibWorkspaceContext, WibWorkspaceSystemContextFactory>();

I want two different factories for the same DbContext. One factory always signs in using a SQL "admin" account and the other uses user-specific accounts.

I can't seem to figure out how to get this to work, though. How can I specify which one to use on the side of things that grab the service? For example, here's a constructor receiving the service - how does it know which one to use?

public async Task Invoke(HttpContext httpContext, IDbContextFactory<WibWorkspaceContext> contextFactory, IConfiguration configuration)

Is this possible?

halfer
  • 19,824
  • 17
  • 99
  • 186
Ryan
  • 7,733
  • 10
  • 61
  • 106
  • perhaps this would help https://stackoverflow.com/questions/42616408/entity-framework-core-multiple-connection-strings-on-same-dbcontext – iSR5 Dec 07 '22 at 06:29
  • another one https://stackoverflow.com/questions/36816215/dynamically-change-connection-string-in-asp-net-core – iSR5 Dec 07 '22 at 06:31
  • Just register the child classes instead of the parent – Tseng Dec 07 '22 at 08:08
  • The DI system distinguishes by type so it has no way to know which implementation to inject (well it'll inject the last one by default) – davidfowl Dec 07 '22 at 08:16

0 Answers0