【发布时间】:2011-09-14 10:30:47
【问题描述】:
我一直在努力解决这个问题,基本上我正在尝试实现一个通用的存储库工厂,它的调用如下:
var resposFactory = new RepositoryFactory<IRepository<Document>>();
存储库工厂如下所示:
public class RepositoryFactory<T> : IRepositoryFactory<T>
{
public T GetRepository(Guid listGuid,
IEnumerable<FieldToEntityPropertyMapper> fieldMappings)
{
Assembly callingAssembly = Assembly.GetExecutingAssembly();
Type[] typesInThisAssembly = callingAssembly.GetTypes();
Type genericBase = typeof (T).GetGenericTypeDefinition();
Type tempType = (
from type in typesInThisAssembly
from intface in type.GetInterfaces()
where intface.IsGenericType
where intface.GetGenericTypeDefinition() == genericBase
where type.GetConstructor(Type.EmptyTypes) != null
select type)
.FirstOrDefault();
if (tempType != null)
{
Type newType = tempType.MakeGenericType(typeof(T));
ConstructorInfo[] c = newType.GetConstructors();
return (T)c[0].Invoke(new object[] { listGuid, fieldMappings });
}
}
}
当我尝试调用 GetRespository 函数时,以下行失败
Type newType = tempType.MakeGenericType(typeof(T));
我得到的错误是:
ArgumentException - GenericArguments[0], 'Framework.Repositories.IRepository`1[Apps.Documents.Entities.PerpetualDocument]', on 'Framework.Repositories.DocumentLibraryRepository`1[T]' 违反了类型 'T' 的约束.
对这里出了什么问题有什么想法吗?
编辑:
仓库的实现如下:
public class DocumentLibraryRepository<T> : IRepository<T>
where T : class, new()
{
public DocumentLibraryRepository(Guid listGuid, IEnumerable<IFieldToEntityPropertyMapper> fieldMappings)
{
...
}
...
}
IRepository 看起来像:
public interface IRepository<T> where T : class
{
void Add(T entity);
void Remove(T entity);
void Update(T entity);
T FindById(int entityId);
IEnumerable<T> Find(string camlQuery);
IEnumerable<T> All();
}
【问题讨论】:
-
您那里缺少退货声明吗?您是否粘贴了该方法的完整副本?
-
另外,当您明确打算调用带参数的构造函数时,为什么还要检查是否存在无参数构造函数?如果你有一个无参数的构造函数,它很可能是
GetConstructors返回的第 0 个构造函数,在这种情况下,使用参数调用它会失败。 -
是的,抱歉,'return default(T)' 应该放在最后。
-
关于无参数构造函数的检查?你说的是对的,我只是想看看我是不是做错了什么。
标签: c# .net generics reflection factory-pattern