【发布时间】:2017-09-07 11:41:12
【问题描述】:
我使用存储库模式设计了一些应用程序。我有一个通用存储库:
public interface IGenericRepository<T> where T : class { // ... }
public class GenericRepository <T> : IGenericRepository<T> where T : class {// ... }
例如,我有两个实体:Order 和 OrderLine。 对于实体“订单”,我只需要通用存储库方法,所以没关系。 但是对于实体“OrderLine”,我需要一些通用存储库方法和一些附加方法。因此,我创建了一个自定义存储库,它扩展了泛型:
public interface IOrderLinesRepository : IGenericRepository<OrderLine> {...}
public class OrderLinesRepository : GenericRepository<OrderLine>, IOrderLinesRepository
{
//... this is my additional methods here
}
但现在我想创建一个方法,它将按实体类型返回一个存储库。 如果实体有自定义存储库 - 应该重新调整它。如果不是,方法必须返回 GenericRepository。这是我尝试创建的。
public sealed class RepositoryFactory
{
// Here is custom repository types
private IDictionary<Type, Func<DbContext, object>> GetCustomFactories()
{
return new Dictionary<Type, Func<DbContext, object>>
{
{ typeof(OrderLine), dbContext =>
new OrderLinesRepository(dbContext) },
};
}
// Custom repository types
private IDictionary<Type, Type> GetRepositoryTypes()
{
return new Dictionary<Type, Type>
{
{ typeof(OrderLine), typeof(IOrderLinesRepository) }
};
}
private Func<GoodWillDbContext, object> GetDefaultFactory<T>()
where T : class
{
return dbContext => new GenericRepository<T>(dbContext);
}
private Func<DbContext, object> GetFactory<T>() where T : class
{
Func<DbContext, object> factory;
var factories = GetCustomFactories();
factories.TryGetValue(typeof(T), out factory);
return factory ?? (factory = GetDefaultFactory<T>());
}
public Type GetRepoType(Type type)
{
var types = GetRepositoryTypes();
Type repoType;
types.TryGetValue(type, out repoType);
return repoType;
}
public object MakeRepository<U>(DbContext dbContext) where U : class
{
// Get repository type
// If custom type not found, it should be standart type
// IGenericRepository<U>
var type = _repositoryFactory.GetRepoType(typeof(U)) ??
typeof(IGenericRepository<U>);
var f = _repositoryFactory.GetFactory<U>();
var repo = f(dbContext);
return repo;
}
}
但由于某种原因它不起作用。我有一些疑问: 1. MakeRepository 应该是什么类型的返回值? 2. 我应该如何转换 var repo = f(dbContext);到存储库类型?
或者也许还有其他方法可以满足我的需要?
【问题讨论】:
-
所以应该使用
GetRepoType返回的类型来查找repo? -
是的,你在写。
-
But it's not working for some reason.是什么原因?什么具体不起作用? -
我不明白,如何将对象 repo 转换为存储库类型。