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...
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With