You can access the current user through the IHttpContextAccessor service, and then execute the CompanyId request:
services.AddScoped(provider => {
var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
var options = optionsBuilder.UseSqlServer(Configuration.GetConnectionString("MyDbDatabase")).Options;
var user = provider.GetRequiredService<IHttpContextAccessor>().HttpContext.User;
int? companyId = int.TryParse(user.FindFirstValue("CompanyId"), out var companyId) ? companyId : (int?)null;
return new DocContext(options, companyId);
});
Note that CompanyId is null. If the user is not authenticated, then CompanyId is null.
: Identity, IHttpContextAccessor. .