How to inject a scoped service into DbContext? Net Core

.net-core asp.net-core c# entity-framework-core

Question

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

1
2
2/9/2018 12:32:28 AM

Accepted Answer

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")
6
2/9/2018 3:23:30 AM

Popular Answer

I am assuming for multi-tenant application you are trying to find out Tenant based on logged in user from HttpRequest. 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

You also have to register UserContext

services.AddScoped<UserContext, UserContext>();

then use constructor injection to inject UserContext wherever you need



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow