Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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...

like image 368
Marek Urbanowicz Avatar asked Dec 01 '22 10:12

Marek Urbanowicz


1 Answers

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. e. g.

services.AddScoped<UserContext, UserContext>();
services.AddEntityFrameworkNpgsql()
                .AddDbContext<MultiTenantContext>(o =>
                    o.UseNpgsql(Configuration.GetConnectionString("DbContext")
like image 85
Christian Gollhardt Avatar answered Dec 05 '22 01:12

Christian Gollhardt