I need to be able create a DBContext with a specific DB connection string depending on the logged in user.
Users login via a JWT token at which point the application makes a call to a 3rd party to determine which database they should be connected to.
I am currently registering my ApplicationDBContext at startup:
services.AddDbContextFactory<ApplicationDBContext>(options => options.UseSqlServer(
Configuration.GetConnectionString("TestDbConString"),
h => h.UseHierarchyId()
));
I also have this service:
services.
...
.onAuthenticated(async c => {
await getConnectionData(); // Returns the connection string. This can take a few seconds the first time subsequently it returns cached data.
})
Obviously I need to change things up a bit. How would you go about registering ApplicationDBContext with the correct/custom connection string?
UPDATE:
Here is my poor attempt at setting up a DbContextFactory.
using Microsoft.EntityFrameworkCore;
using MyApp.Models;
namespace MyApp.Data
{
public class ApplicationDbContextFactory : IDbContextFactory<AppDbContext>
{
public ApplicationDbContextFactory test(){
return new ApplicationDbContextFactory();
}
public AppDbContext CreateDbContext()
{
string ConnectionString = "";
//Magic here to get my ConnectionString.
DbContextOptionsBuilder<AppDbContext> options = new DbContextOptionsBuilder<AppDbContext>();
options.UseSqlServer(
ConnectionString,
h => h.UseHierarchyId()
);
return new AppDbContext(options.Options);
}
}
}
Startup,cs
services.AddTransient<ApplicationDbContextFactory>();
services.AddTransient(provider => provider.GetService<ApplicationDbContextFactory>()!.CreateDbContext());
I am now getting an error:
Unexpected Execution Error : No service for type 'Microsoft.EntityFrameworkCore.IDbContextFactory`1[MyApp.Data.AppDbContext]' has been registered.
Update #2 This fixed it:
Startup.cs
services.AddTransient<IDbContextFactory<AppDbContext>, ApplicationDbContextFactory>();