Reputation: 1046
I am using the DbContextScope described here
In his example of how to get a hold of a dbcontext outside of the class its instantiated, Mehdi writes:
public class UserRepository : IUserRepository {
private readonly IAmbientDbContextLocator _contextLocator;
public UserRepository(IAmbientDbContextLocator contextLocator)
{
if (contextLocator == null) throw new ArgumentNullException("contextLocator");
_contextLocator = contextLocator;
}
public User Get(Guid id)
{
return _contextLocator.Get<MyDbContext>.Set<User>().Find(id);
}
}
But, if im going for a generic repository, say
public abstract class RepositoryBase<T> : IRepository<T> where T : class, IDomainEntity
{
private readonly DbSet<T> set;
private IAmbientDbContextLocator contextLocator;
protected RepositoryBase(IAmbientDbContextLocator ctxLocator)
{
if (ctxLocator == null) throw new ArgumentNullException(nameof(ctxLocator));
contextLocator = ctxLocator;
}
public T Get(Guid id)
{
//return _contextLocator.Get<MyDbContext>.Set<T>().Find(userId);
}
}
then how is the dbset supposed to be resolved? how do i work with "MyDbContext" in the Get method? i do have multiple contexts.
Upvotes: 2
Views: 1348
Reputation: 4382
public abstract class RepositoryBase<T, TDbContext> : IRepository<T> where T : IDomainEntity where TDbContext : DbContext
{
private readonly DbSet<T> _dbset;
private readonly IAmbientDbContextLocator _contextLocator;
protected RepositoryBase(IAmbientDbContextLocator ctxLocator)
{
if (ctxLocator == null) throw new ArgumentNullException(nameof(ctxLocator));
_contextLocator = ctxLocator;
_dbset = _contextLocator.Get<TDbContext>.Set<T>();
}
protected DbSet<T> DbSet { get { return _dbset; } }
public T Get(Guid id)
{
return DbSet.Find(id);
}
}
If you don't want TDbContext
, You can send DbContext
on constructor beside of contextlocator
. But he forces you to use DbContextScope
, I didn't read all article but let's not break his logic.
Upvotes: 3