首页 > 解决方案 > 创建 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>();

        }

标签: .net-coredependency-injection

解决方案


尝试将此行添加到服务注册中:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

或者

services.AddHttpContextAccessor();

此链接显示了访问方式HttpContext

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-3.1


推荐阅读