带有Generic Repository的DbContextScope

时间:2016-03-08 11:34:42

标签: c# entity-framework generics repository-pattern dbcontext

我正在使用描述here

的DbContextScope

在他的示例中,如何在类实例化之外获取dbcontext,Mehdi写道:

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);
    } 
}

但是,如果我要使用通用存储库,请说

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);
    }
}

然后如何解决dbset?我如何在Get方法中使用“MyDbContext”? 我确实有多种情境。

1 个答案:

答案 0 :(得分:2)

   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);
        }
    }

如果您不想TDbContext,可以在DbContext旁边的构造函数上发送contextlocator。但他强迫你使用DbContextScope,我没有阅读所有文章但是不要打破他的逻辑。