[英]EF Core, DI, Repository pattern and issue with base repository structure
[英]Repository Pattern with Generic interface and DI in EF
我有这个现有的代码
public interface IRepository<T>
{
void Create(T obj);
T Retrieve(string key);
}
public class ItemRepository : IRepository<Item>
{
public void Create(Item obj)
{
//codes
}
public Item Retrieve(string key)
{
//codes
}
}
我想创建一个通用类存储库,在该类存储库中,我必须向构造函数中注入IRepository类型,然后使用其自己的方法实现。 我已经有一个现有的代码,但目前是错误的
public class Repository
{
IRepository<T> action = null;
public Repository(IRepository<T> concreteImplementation)
{
this.action = concreteImplementation;
}
public void Create(T obj)
{
action.Create(obj);
}
}
这些课程来自EF。 如果没有解决办法,最好的方法是什么?
如果我理解正确,那么您需要一个可以通过委派特定于类型的存储库实现来创建或检索任何类型的对象的存储库吗?
您如何看待这项工作? 您定义了此Repository
类,但是必须使用它来创建实际存储库的具体实现,然后仍然必须创建Repository
的实例。 为什么不只使用您必须创建的通用实现呢?
那您的Retrieve
方法呢? 这在您的Repository
类中看起来如何? 您会只返回Object
吗? 还是会让您的方法通用?
无论如何回答您的问题,我都可以这样做:
public class Repository
{
IRepository action = null;
public Repository(IRepository concreteImplementation)
{
this.action = concreteImplementation;
}
public void Create<T>(T obj)
{
action.Create(obj);
}
}
但您还必须引入一个非通用接口,因为在不指定类的通用类型的情况下,构造函数中不需要具有通用参数的接口。
public interface IRepository
{
void Create(object obj);
object Retrieve(string key);
}
或者,您可以将类型传递给Create方法,而不要使用通用参数:
public class Repository
{
IRepository action = null;
public Repository(IRepository concreteImplementation, Type respositoryType)
{
this.action = concreteImplementation;
expectedType=repositoryType;
}
public void Create(Type type, Object obj)
{
if(type==expected && obj.GetType()==type)
{
action.Create(obj);
}
}
}
但是这两个都是可怕的想法。 只需使用泛型并为每种类型创建一个存储库,从长远来看最好
我认为您可能只是在一般存储库类的上下文中缺少T
的定义。
尝试像这样向其中添加<T>
:
public class Repository<T>
{
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.