I'm building ASP.NET Core Web Api with Simple Injector and have the following problem: The data for each user is stored in his individual base (but with the same schema), which is known only after he authorizes himself. So... I can give DbContext
it's proper connection string only after user's authorization. What is the best way to accomplish this?
For now I am storing the connection string in HttpContext
custom claim and am refering to it with a use of a static helper class in DbContext
's OnConfiguring method.
The helper:
public class WebHelper
{
private static IHttpContextAccessor _httpContextAccessor;
public static void Configure(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
private static HttpContext HttpContext
{
get
{
return _httpContextAccessor.HttpContext;
}
}
public static string ConnectionString
{
get
{
return _httpContextAccessor?.HttpContext?.User.FindFirst(CustomClaimTypes.ConnectionString)?.Value;
}
}
}
Which I have registered like this:
private SimpleInjector.Container _container = new SimpleInjector.Container();
public void ConfigureServices(IServiceCollection services)
{
_container.Register(() =>
{
return new BaseDbContext(SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(),
"Data Source=127.0.0.1").Options);
}, Lifestyle.Scoped);
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
WebHelper.Configure(app.ApplicationServices.GetRequiredService<IHttpContextAccessor>());
}
And after all I am calling the connection string like this:
public class BaseDbContext : DbContext
{
public BasetDbContext(DbContextOptions options)
: base(options) { }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (WebHelper.ConnectionString != null)
{
optionsBuilder.UseSqlServer(WebHelper.ConnectionString);
}
}
}
And I am not exactly satisfied with this approach, so I want to ask if anyone has a better idea...