.net-core - 创建 ApplicationDbContext 时 HttpContext 为空
问题描述
我正在尝试在我的 Core 3.1 MVC 应用程序中实现多租户。我看到如下示例,但是当我运行我的应用程序时,HttpContext 为空,我不明白为什么。唯一的区别是我使用 ApplicationDbContext 但据我所知,它无论如何都继承自 DbContext ......
public class PlaylistContext : DbContext
{
private int _tenantId;
private string _tenantHost;
public DbSet<Playlist> Playlists { get; set; }
public DbSet<Song> Songs { get; set; }
public PlaylistContext(DbContextOptions<PlaylistContext> options,
IHttpContextAccessor accessor)
: base(options)
{
_tenantHost = accessor.HttpContext.Request.Host.Value;
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var connection = Database.GetDbConnection();
using (var command = connection.CreateCommand())
{
connection.Open();
command.CommandText = "select ID from Tenants where Host=@Host";
command.CommandType = CommandType.Text;
var param = command.CreateParameter();
param.ParameterName = "@Host";
param.Value = _tenantHost;
command.Parameters.Add(param);
_tenantId = (int)command.ExecuteScalar();
connection.Close();
}
foreach (var type in GetEntityTypes())
{
var method = SetGlobalQueryMethod.MakeGenericMethod(type);
method.Invoke(this, new object[] { modelBuilder });
}
base.OnModelCreating(modelBuilder);
}
// Other methods follow
}
我的代码
public ApplicationDbContext(
DbContextOptions<ApplicationDbContext> options,
IHttpContextAccessor http,
ILogger<ApplicationDbContext> logger,
ITenantService tenantService
)
: base(options)
{
_http = http; // <-- _http.HttpContext is null
_logger = logger;
_tenantService = tenantService;
}
我的服务
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options => {
options.UseSqlite(Configuration.GetConnectionString("DefaultConnection"));
options.EnableSensitiveDataLogging(true);
});
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews()
.AddRazorRuntimeCompilation()
.AddNewtonsoftJson(options=>{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
services.AddRazorPages();
services.AddMultiTenancy()
.WithResolutionStrategy<HostResolutionStrategy>()
.WithStore<TenantStore>();
services.AddScoped<ITenantService, TenantService>();
}
解决方案
尝试将此行添加到服务注册中:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
或者
services.AddHttpContextAccessor();
此链接显示了访问方式HttpContext
:
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-3.1
推荐阅读
- java - 写入 Apache POI 工作簿时获取 java.lang.NullPointerException
- javascript - Firebase Auth 登录区别
- css - 向上箭头符号未在 IE 中呈现
- r - 排除基于 R 中多列的异常值?IQR 方法
- json - 如何快速解析动态 JSON
- security - 我如何仅通过登录 Gmail 来登录 youtube.com?
- javascript - 是否可以安装预缓存服务器数据的 PWA?
- web-scraping - 网页抓取 Yahoo Finance 推荐评级
- javascript - Javascript函数执行和嵌套函数调用
- doctrine-orm - Doctrine - 删除具有单向多对多关系的实体失败