Reputation: 37909
I want to set the TenantId
in my DbContext
so that I can filter all queries using it.
I have set up the filter, but I am having difficulty getting the TenantId
to the DbContext
.
The reason for the difficulty is that the UserManager
which is used to get the currently logged in user (and thus the TenantId
) depends on the DbContext
to get data from the database. So I cannot import the UserManager
with Dependency Injection because it results in a circular dependency. The UserManager
depends on the DbContext
, and the DbContext
depends on the UserManager
.
Is there some other way to configure this?
Upvotes: 5
Views: 881
Reputation: 1463
If I understand your question correctly you have a situation like this:
public class UserManager : IUserManager
{
public UserManager(IDBContext db, ... )
{
_context = db;
...
}
private IDBContext _context ;
public UserInfo User {get; set;}
// ... Some logic that fills User
}
public class DBContext : IDBContext
{
public DBContext(...)
{
...
}
// ... Here you need UserInfo to filter.
}
Change the structure of you application a little, and make it like this:
public class UserProvider : IUserProvider
{
public UserInfo User {get; set;}
}
public class UserManager : IUserManager
{
public UserManager(IDBContext db, IUserProvider provider, ... )
{
_context = db;
_userProvider = provider;
...
}
private IDBContext _context ;
private IUserProvider _userProvider;
// ... Some logic that fills _userProvider.UserInfo
}
public class DBContext
{
public DBContext(IUserProvider provider, ...)
{
_userProvider = provider;
...
}
private IUserProvider _userProvider;
// ... Here you can use _userProvider.UserInfo
}
Only requirement: Register IUserProvider as a singleton in your Dependancy Injection Framework
Upvotes: 2