如何将范围服务注入DbContext?网络核心 [英] How to inject a scoped service into DbContext? Net Core

查看:226
本文介绍了如何将范围服务注入DbContext?网络核心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建多租户应用程序,并试图使数据安全性现在起作用。
Context的单元测试效果很好,因为我使用选项和UserContext创建了上下文,但是由于要注入userContext,我很难使它在程序集中运行。

I am building the multi tenant app and trying to get the data security working now. Unit tests of Context are working nice because I create the context with options and UserContext, but I am struggling to get it working in assembly as it needs userContext to be injected.

我不能像其他任何东西一样使用标准控制器注入,就像我拥有它一样,上下文创建失败:

I cannot use standard controller injection as with everything else, as if I have it, the context creation fails:

services.AddEntityFrameworkNpgsql()
                .AddDbContext<MultiTenantContext>(o =>
                    o.UseNpgsql(Configuration.GetConnectionString("DbContext")

我不能或者我不知道如何以这种方式注入UserContext ...

I cannot or I do not know how to inject my UserContext this way...

推荐答案

简单使用构造函数注入。它的工作方式与在控制器中相同。

Simple use constructor injection. It is working the same way like in a controller.

public class MultiTenantContext : DbContext
{
    private UserContext _userContext;

    public MultiTenantContext(DbContextOptions options, UserContext userContext) : base(options)
    {
        _userContext = userContext;
    }
}

您需要确保注册 UserContext 服务,然后再注册实体框架。 e。 g。

You need to make sure, that you register the UserContext service before you are registering the entity framework. e. g.

services.AddScoped<UserContext, UserContext>();
services.AddEntityFrameworkNpgsql()
                .AddDbContext<MultiTenantContext>(o =>
                    o.UseNpgsql(Configuration.GetConnectionString("DbContext")

这篇关于如何将范围服务注入DbContext?网络核心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆