【发布时间】:2019-09-03 16:34:09
【问题描述】:
我有一个基础存储库设置。我想创建一个通用的通用存储库以使用一个返回布尔值的通用方法:
DoesRecordExist()
我有基本 repo 和 common repo 设置,但我在引用服务中的 ICommonRepository 时遇到问题。这个方法怎么调用?
BaseRepository:
public abstract class BaseRepository<TModel> : IBaseRepository<TModel> where TModel : BaseClass
{
private readonly IDbContext _context;
private readonly IValidator<TModel> _validator;
public BaseRepository(IDbContext context, IValidator<TModel> validator = null)
{
_context = context;
_validator = validator ?? new InlineValidator<TModel>();
}
public bool DoesRecordExist(Guid id)
{
return _context.Set<TModel>().Any(x => x.Guid == id);
}
}
CommonRepository:
public class CommonRepository<TModel> : BaseRepository<TModel> where TModel : BaseClass, ICommonRepository<TModel>
{
private readonly IDbContext _context;
private readonly IValidator<TModel> _validator;
public CommonRepository(IDbContext context, IValidator<TModel> validator = null) : base(context, validator)
{
_context = context;
_validator = validator ?? new InlineValidator<TModel>();
}
public bool CommonDoesRecordExist(Guid id)
{
return DoesRecordExist(id);
}
}
全球服务:
private readonly ICategoryRepository _categoryRepository;
private readonly ISubcategoryRepository _subCategoryRepository;
private readonly ISubcategoryDescriptionRepository _subcategoryDescriptionRepository;
private readonly ICommonRepository<??????> _commonRepository;
public GlobalDataService(
ICategoryRepository categoryRepository,
ISubcategoryRepository subCategoryRepository,
ISubcategoryDescriptionRepository subcategoryDescriptionRepository,
ICommonRepository<????> commonRepository)
{
_categoryRepository = categoryRepository;
_subCategoryRepository = subCategoryRepository;
_subcategoryDescriptionRepository = subcategoryDescriptionRepository;
_commonRepository = commonRepository;
}
public bool DoesUserRecordExist(Guid userId)
{
//PROBLEM ON THIS LINE... bool existingData = _commonRepository.CommonDoesRecordExist(userId);
if (existingData)
{
//do stuff
}
else
{
//do other stuff
}
}
ICommonRepository.cs
public interface ICommonRepository<T> : IBaseRepository
{
bool CommonDoesRecordExist(Guid id);
}
IBaseRepository.cs
public interface IBaseRepository<T> : IBaseRepository
{
bool DeleteAll();
bool DoesRecordExist(Guid id, Expression<Func<T, bool>> filter);
List<T> GetAll();
T GetOne(Guid id);
T Save(T item);
bool Delete(Guid id);
bool Delete(T item);
IQueryable<T> Include(params Expression<Func<T, object>>[] includes);
}
public interface IBaseRepository
{
string CollectionName { get; }
}
【问题讨论】:
-
是 _commonRepository 是 BaseRepository 类型吗?
-
@stinepike 是的,它表明在我相信的代码示例中
-
你为什么不直接调用 _commonRepository.DoesRecordExist 呢?
-
@stinepike 现在我不知道如何定义 _commonRepository 来调用它
-
然后您将需要一个具有通用方法的工厂来获取所需的存储库
标签: c# oop generics abstract-class