【问题标题】:A c# Generics question involving Controllers and Repositories一个涉及控制器和存储库的 c# 泛型问题
【发布时间】:2010-05-28 08:02:36
【问题描述】:

我有一个基础存储库类,其中包含所有常见的存储库方法(作为通用):

public abstract class BaseRepository<T, IdType> : IBaseRepository<T, IdType>

我来自这个基础的存储库,例如:

public class UserRepository : BaseRepository<User, int>, IUserRepository

我还有一个包含通用操作的基本控制器类,并在控制器中继承自它。存储库由 DI 注入其中。例如

public class UserController : BaseController<User>
{
        private readonly IUserRepository userRepository;

        public UserController (IUserRepository userRepository)
        {
            this.userRepository= userRepository;
        }

我的问题是:基本控制器需要能够访问基本存储库中定义的存储库方法。但是,我通过 DI 为每个控制器传入了不同的存储库类型(即使它们都继承自基本存储库)。基控制器如何以某种方式访问​​传入的存储库(无论它是什么类型),以便它可以访问常用的基方法?

【问题讨论】:

  • ctor 上的 I 是否意味着在场上?
  • @marc 是的,抱歉 - 错字(在真实代码中可以) - 我会更新帖子。

标签: c# asp.net-mvc generics repository


【解决方案1】:

您所有的存储库都将派生自IBaseRepository&lt;T,IdType&gt;,然后有:

interface IUserRepository : IBaseRepository<User,int> {...}

现在任何对IUserRepository 的引用都会知道IBaseRepository&lt;&gt; 成员,而不必提及UserRepository 类或BaseRepository&lt;&gt; 类等具体类型。

【讨论】:

  • 嗨,Marc,是的,我没有在我的帖子中展示它,但我已经从 IBaseRepository 继承了 IUserRepository。
  • @UpTheCreek - 如果你的意思是你需要来自BaseRepository&lt;&gt;(类)的方法,那么你已经打破了抽象到接口的要点......如果你的意思是IBaseRepository&lt;&gt;接口,它应该已经工作了。
【解决方案2】:

您可以在BaseController 中保留BaseReposiroty 的参考

public class BaseController <T, IdType>
{
    ...
    ...
    protected BaseRepository<T, IdType> Reposirory
    {
        { get; set; }
    }
    ...
    ...
}

【讨论】:

  • 嗨 Itay,这就是我想要做的 - 但是当我传入子类存储库时如何获得这个引用?
  • 我不明白你的问题
【解决方案3】:

这是一种方法..

public abstract class BaseController<TEntity, TRepository, TIdType>
    where TEntity : class, new()
    where TRepository : IBaseRepository<TEntity, TIdType>
{
    protected TRepository Repository = RepositiryFactory.GetRepository<TEntity, TRepository>();

    public IList<TEntity> GetAll()
    {
        return Repository.GetAll().ToList();
    }
    public IList<TEntity> GetAll(string sortExpression)
    {
        return Repository.GetAll(sortExpression).ToList();
    }
    public int GetCount()
    {
        return Repository.GetAll().Count();
    }
    public IList<TEntity> GetAll(int startRowIndex, int maximumRows)
    {
        var results = Repository.GetAll().Skip(startRowIndex).Take(maximumRows);
        return results.ToList();
    }
    public IList<TEntity> GetAll(string sortExpression, int startRowIndex, int maximumRows)
    {
        var results = Repository.GetAll(sortExpression).Skip(startRowIndex).Take(maximumRows);
        return results.ToList();
    }
}

【讨论】:

    猜你喜欢
    • 2011-03-21
    • 2011-03-23
    • 1970-01-01
    • 2011-02-23
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    相关资源
    最近更新 更多