为了简化我的代码,我想知道是否有一种方法可以将我的存储库类作为其继承的基类传递
Repository<TEntity>
,它使用泛型,使用多态性。我明白为什么我的代码不起作用,但我想知道我是否遗漏了一些东西,以及是否可以将多个存储库类作为 Repository<TEntity>
传递以使用其方法。
我在这里手动输入了这段代码。如果我编辑错误请告诉我。
基础存储库类,使用实体框架上下文类...
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
protected readonly DbContext Context;
public Repository(DbContext context)
{
this.Context = context;
}
public IEnumerable<TEntity> MethodOne()
{
return Context.Set<TEntity>().DoSomething();
}
public IEnumerable<TEntity> MethodTwo()
{
...
}
}
存储库示例...
internal class SomeModelRepository : Repository<SomeModel>
{
public __DbContext DbContext
{
get { return Context as __DbContext; }
}
public SomeModelRepository(__DbContext context) : base(context) { }
}
工作单元类...
internal class UnitOfWork : IUnitOfWork
{
private readonly __DbContext _context;
public SomeModelRepository SomeModels { get; private set; }
public SomeOtherModelRepository SomeOtherModels { get; private set; }
public UnitOfWorkProject(__DbContext context)
{
_context = context;
SomeModels = new SomeModelRepository(context);
SomeOtherModels = new SomeOtherModelRepository(context);
}
...
}
想要对一堆 EF 模型执行相同操作的客户端类。多态性在这里不起作用,因为即使 SomeModelRepository 继承了
Repository<TEntity>
,也无法将 SomeModelRepository 作为 Repository<TEntity>
传递。这并不奇怪,但是有没有办法传递多个存储库类型并在 Repository<TEntity>
类中调用相同的方法?
public class Client
{
UnitOfWork _UnitOfWork;
public Client()
{
UnitOfWork _UnitOfWork = new(new __DbContext());
}
public void DoSomeClientStuff()
{
//Of course, this doesn't work
ClientMethod(new List<Repository<object>> { _UnitOfWork.SomeModels, _UnitOfWork.SomeOtherModels });
_UnitOfWork.SaveChanges();
}
private void ClientMethod(IEnumerable<Repository<object>> repositories)
{
foreach (Repository<object> repository in repositories)
{
repository.MethodOne();
repository.MethodTwo();
}
}
}
不清楚您是否有权访问
IRepository<TEntity>
接口定义还是使用 EF 定义的?
如果你可以更新接口,你可以使用协方差。
public interface IRepository<out TEntity>
{
IEnumerable<TEntity> MethodOne();
IEnumerable<TEntity> MethodTwo();
}
然后,在
Client
类中使用协变接口
public class Client
{
UnitOfWork _UnitOfWork;
public Client()
{
UnitOfWork _UnitOfWork = new(new __DbContext());
}
public void DoSomeClientStuff()
{
//Of course, this doesn't work
ClientMethod(new List<IRepository<object>> { _UnitOfWork.SomeModels, _UnitOfWork.SomeOtherModels });
_UnitOfWork.SaveChanges();
}
private void ClientMethod(IEnumerable<IRepository<object>> repositories)
{
foreach (IRepository<object> repository in repositories)
{
repository.MethodOne();
repository.MethodTwo();
}
}
}