【问题标题】:Cannot access repository base class methods无法访问存储库基类方法
【发布时间】:2011-05-10 04:52:02
【问题描述】:

在我的特定存储库类中,例如 CollectionRepository,我继承了通用基类 (BaseRepository),并在构造函数中使用了应该注入的基 UnitOfWork。但是,我无法访问任何 BaseRepository 继承的方法。

完全没有想法,任何帮助将不胜感激。

这里有一些代码来说明我的问题:

我的存储库被注入的控制器。

public readonly ICollectionRepository _collectionRepository;

public HomeController(ICollectionRepository collectionRepository, IRepository<Collection> repository)
{
  _collectionRepository = collectionRepository;
}

public ActionResult Index()
{
  _collectionRepository. //Here i only get the ICollectionRepositoryMethods

  return View(new List<Note>());
}

我的基础仓库:

public class BaseRepository<T> : IRepository<T> where T : IAggregateRoot
{
  public readonly IUnitOfWork _unitOfWork;

  public BaseRepository(IUnitOfWork unitOfWork)
  {
    _unitOfWork = unitOfWork; 
  } 

  public BaseRepository()
  {}

  public void Save(T Entity)
  {
    _unitOfWork.Session.Save(Entity);
  }
}

继承基础的特定存储库类。

public class CollectionRepository : BaseRepository<Collection>, ICollectionRepository
{
  public CollectionRepository(IUnitOfWork unitOfWork) : base(unitOfWork)
  {
  }

  public IList<Collection> GetTodaysCollections()
  {
    throw new System.NotImplementedException();
  }
}

我正在使用结构映射像这样配置 CollectionRepository,不确定这是否正确:

For<ICollectionRepository>().Use<CollectionRepository>();

【问题讨论】:

    标签: c# inheritance repository-pattern structuremap


    【解决方案1】:

    您可以为 ICollectionRepository 实现的 BaseRepository 引入一个接口。

    这将使处理 ICollectionRepository 的任何东西都知道 BaseRepository 方法。

    public interface IBaseRepository<T>
    {
        void Save(T Entity);
    }
    

    BaseRepository 实现了:

    public class BaseRepository<T> : IBaseRepository<T>, IRepository<T> where T : IAggregateRoot
    

    现在当ICollectionRepository 实现该接口时,所有实现ICollectionRepository 的类也实现IBaseRepository

    public ICollectionRepository<T> : IBaseRepository<T>
    {
        //ICollectionRepository methods go here...
    }
    

    由于您的CollectionRepository 继承自实现IBaseRepository 接口的BaseRepository,因此您已经满足要求,现在可以调用基类方法。

    【讨论】:

    • @David Hall 抱歉回复晚了,我已经有你建议的基本接口,我只是将其称为 IRepository(为清楚起见,它应该称为 IBaseRepository)。还有其他建议吗?
    • @geepie 您的 ICollectionRepository 是否也实现了 IRepository?这是我回答中的主要建议。
    • @David Hall 不,它不需要,但它不需要,我之前已经这样做并使用了 BaseRepository 中的通用方法,而不必再次实现接口(IRepository)在我特定的 CollectionRepository 中
    • @geepie 也许你可以加入聊天?我在 C# 房间里
    • @geepie 基本上是作为 ICollectionRepository 传入的,你确实没有有一个 CollectionRepository,所以 CollectionRepository 从 BaseRepository 继承并不重要,因为 ICollectionRepository 没有任何 BaseRepository方法。这就是为什么我建议通过实现将这些方法提供给 BaseRepository 的接口将这些方法添加到 ICollectionRepository。在处理 ICollectionRepository 时,我不知道有任何其他方法可以访问这些方法(好吧,除了强制转换之外,这完全破坏了您尝试使用 DI 所做的事情)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-04
    • 2013-09-05
    • 1970-01-01
    • 2022-07-21
    相关资源
    最近更新 更多