简体   繁体   English

如何将范围服务注入DbContext? 网络核心

[英]How to inject a scoped service into DbContext? Net Core

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. Context的单元测试工作得很好,因为我使用选项和UserContext创建了上下文,但是由于需要注入userContext,因此我很难使它在程序集中工作。

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")

I cannot or I do not know how to inject my UserContext this way... 我不能或不知道如何以这种方式注入我的UserContext ...

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;
    }
}

You need to make sure, that you register the UserContext service before you are registering the entity framework. 您需要确保在注册实体框架之前先注册UserContext服务。 eg 例如

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

I am assuming for multi-tenant application you are trying to find out Tenant based on logged in user from HttpRequest. 我假设对于多租户应用程序,您正在尝试根据HttpRequest中登录的用户找出Tenant You can do something like this 你可以做这样的事情

public class UserContext
{
    private readonly IHttpContextAccessor _accessor;
    public RequestContextAdapter(IHttpContextAccessor accessor)
    {
        this._accessor = accessor;
    }

    public string UserID
    {
        get
        {
            // you have access to HttpRequest object here
            //this._accessor.HttpContext.Request
        }
    }
}

ASP.NET Core will automatically inject IHttpContextAccessor into UserContext ASP.NET Core将自动将IHttpContextAccessor注入UserContext

You also have to register UserContext 您还必须注册UserContext

services.AddScoped<UserContext, UserContext>();

then use constructor injection to inject UserContext wherever you need 然后使用构造函数注入在需要的地方注入UserContext

The accepted answer didn't work for me as well, I ended up doing a very similar approach to the original answer, thanks @Christian for your guidance. 接受的答案对我也不起作用,我最终对原始答案采取了非常相似的方法,感谢@Christian的指导。

I wanted to inject a service into the DbContext which is responsible to load connection string dynamically based on some HTTP request header below is the code used 我想将服务注入到DbContext中,该服务负责根据某些HTTP请求标头动态加载连接字符串,以下是使用的代码

In Startup: 在启动中:

  services.AddScoped<IConnectionService, ConnectionService>();
  services.AddDbContext<MyDbContext>(); //Connection string will be set on event OnConfiguring

In MyDbContext: 在MyDbContext中:

public class MyDbContext : DbContext
    {
        private readonly IConnectionService _connectionService;

        public MyDbContext(DbContextOptions<MyDbContext> options, IConnectionService connectionService) : base(options)
        {
            _connectionService = connectionService;
        }

        public DbSet<Customer> Customers { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            var connectionString = _companyConnectionService.ConnectionString; //Custom logic to read from http request header certain value and switch connection string
            optionsBuilder.UseSqlServer(connectionString);
        }
    }

Hope this will help. 希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 .NET 核心 DI 允许将作用域服务注入本地机器上的 singleton - .NET Core DI allowing to inject scoped service into singleton on local machine 如何在.NET Core Console应用程序中处理Scoped服务实例? - How is a Scoped service instance handled in a .NET Core Console application? 如何在Repository中注入EntityFramework Core DbContext - How to inject EntityFramework Core DbContext in Repository 如何访问 asp.net 核心服务的 DbContext - How to access the DbContext fom asp.net core service .net 核心中的范围服务 DI 和 GC - 澄清? - Scoped service DI & GC in .net CORE - Clarification? 如何在startup.cs的ConfigureServices方法中正确注入DbContext实例(ASP.net core 1.1)? - How to inject DbContext instance in the ConfigureServices method of startup.cs correctly (ASP.net core 1.1)? Net核心通用存储库模式如何在编译时不知道其类型的情况下注入DbContext? - Net core generic repository pattern how to inject DbContext without knowing its type at compile time? 如何在 EF Core 中具有范围 Dbcontext 时实现数据库弹性? - How to implement database resiliency while having a scoped Dbcontext in EF Core? ASP.NET Core解决服务中的DbContext - ASP.NET Core resolving DbContext in Service ASP.NET BoilerPlate:如何在应用程序服务中注入DbContext对象? - ASP.NET BoilerPlate: How do I inject object of DbContext in application service?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM