如何在存储库模式(MVC)中有多个 类

how to have multiple classes in repository pattern (MVC)

我对存储库模式有点困惑,在这里我写我的代码然后我解释一下:

 public  interface IRepositoryTest<T> where T:class
{
  IEnumerable<T> SelectAll(Expression<Func<T, bool>> predicate);

}

这里是上面签名的实现:

 public class RepositoryTest<T>:IRepositoryTest<T> where T:class
{

    private CentralEntities db = null;
    private DbSet<T> table = null;

    public RepositoryTest() {
    this.db = new CentralEntities();
    table = db.Set<T>();
                        }

    public RepositoryTest(CentralEntities db)
    {

        this.db = db;
        table = db.Set<T>();
    }


    public IEnumerable<T> SelectAll(Expression<Func<T, bool>> predicate)
    {

        return table.Where(predicate).ToList();

    }

}

现在在我的控制器中,如果我想使用这个存储库,我必须做这样的事情:

  IRepositoryTest<UserRoles> _repository = null;

    public DashbrdController(IRepositoryTest<UserRoles> _repository)
    {

        this._repository = _repository;


    }

    public DashbrdController()
    {

        this._repository = new RepositoryTest<UserRoles>();

    }

    public ActionResult DashBrd()
    {

        var rslt = _repository.SelectAll(s=>s.user_id=="myName");         
        return View();

    }

这里的问题是,在我的控制器中,我只能使用模型中的一个 class,如您所见(UserRoles),如果我想向该控制器添加另一个 class 如何我应该这样做吗?我想有多个 class 加入它们,但是在我的控制器的构造函数中我只能使用一个 class,问题出在哪里?

更新:

添加这个 wapper class

class TransactionManager
{
    CentralEntities _ctx;
    Hashtable _repositories;
    public TransactionManager(CentralEntities ctx)
    {
        _ctx = ctx;
    }
    public RepositoryTest<T> CreateRepository<T>() where T : class
    {
        if (_repositories == null)
            _repositories = new Hashtable();
        var type = typeof(T).Name;
        if (!_repositories.Contains(type))
        {
            var repositoryType = typeof(RepositoryTest<>);
            var repositoryInstance = Activator.CreateInstance(repositoryType.MakeGenericType(typeof(T)), _ctx);
            _repositories.Add(type,repositoryInstance);
        }
        return (RepositoryTest<T>)_repositories[type];
    }

    public int Save()
    {
        return _ctx.Save();
    }
}

现在在控制器中

public class DashbrdController:Controller
{ 
 TransactionManager _tMgr;
public DashbrdController(TransactionManager tMgr)
{
    this._tMgr=tMgr;
}

public DashbrdController()
{
    this._tMgr=new TransactionManager() ;
}

public ActionResult DashBrd()
{
    var rslt = _tMgr.CreateRepository<UserRoles>().SelectAll(s=>s.user_id=="myName");         
    return View();
}
public ActionResult AnotherDashBrd()
{
    var anotherrslt = _tMgr.CreateRepository<AnotherRoles>().SelectAll(s=>s.Name=="myName");         
    return View();
}

此外,您可以检查项目的源代码,了解存储库模式

https://github.com/AJEETX/RepositoryPattern