[英]Using generic interface repository
I have my repositories setup like below. 我有如下的存储库设置。
interface IRepository<T> where T : DataRow
{
T Get(int key);
}
interface ICartonRepository : IRepository<CartonDataRow>
{
}
class CartonRepository : ICartonRepository
{
public CartonDataRow Get(int key)
{
}
}
I also have a PackRepository which is defined in the same way as the CartonRepository. 我还有一个PackRepository,它的定义方式与CartonRepository相同。 What I would like to do is something like the following. 我想做的事情如下。
IRepository<DataRow> repository;
switch (rowType)
{
case Carton:
repository = new CartonRepository();
break;
case Pack:
repository = new PackRepository();
break;
}
Is there a way I can achieve this? 有没有办法可以做到这一点?
interface IRepository<out T> where T : DataRow
{
T Get(int key);
}
This requires C# 4.0 though. 但这需要C#4.0。
You require some sort of Factory pattern . 您需要某种工厂模式 。
Following logic should go to Factory class 以下逻辑应进入工厂课堂
class RepositoryFactory
{
IRepository<T> Get(rowType)
{
IRepository<T> repository = default(IRepository<T>);
switch (rowType)
{
case Carton:
repository = new CartonRepository();
break;
case Pack:
repository = new PackRepository();
break;
}
return repository;
}
}
You can further improve Get Method using Dependency Injection or based on maintaining all repositories in dictionary. 您可以使用依赖注入或基于维护字典中的所有存储库来进一步改进Get Method 。
For C# 3.5 you will have to add the following: 对于C#3.5,您将必须添加以下内容:
public interface IRepository {
DataRow Get(int key);
}
public abstract class Repository<T> : IRepository<T>, IRepository
where T : DataRow
{
public abstract T Get(int key);
DataRow IRepository.Get(int key) {
return this.Get(key);
}
}
Then change CartonRepository
to class CartonRepository : Repository<CartonDataRow>
(I do not think you need ICartonRepository
, but you can use it if you want). 然后将CartonRepository
更改为CartonRepository
class CartonRepository : Repository<CartonDataRow>
(我不认为您需要ICartonRepository
,但是您可以根据需要使用它)。 Then 然后
IRepository repository;
switch (rowType)
{
case Carton:
repository = new CartonRepository();
break;
case Pack:
repository = new PackRepository();
break;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.