Tôi đã kéo tóc ra một lúc, về cơ bản tôi đang cố gắng triển khai nhà máy kho chung, được gọi như sau:Generics & Reflection - GenericArguments [0] vi phạm ràng buộc kiểu
var resposFactory = new RepositoryFactory<IRepository<Document>>();
nhà máy kho trông giống như sau:
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 });
}
}
}
Khi tôi cố gắng gọi GetRespository hoạt dòng sau thất bại
Type newType = tempType.MakeGenericType(typeof(T));
Các lỗi tôi nhận được là:
ArgumentException - GenericArguments [0], 'Framework.Repositories.IRepository`1 [Apps.Documents.Entities.PerpetualDocument]', vào 'Framework.Repositories.DocumentLibraryRepository`1 [T] 'vi phạm ràng buộc của loại' T '.
Mọi ý tưởng về những gì xảy ra ở đây?
EDIT:
Việc thực hiện các kho lưu trữ như sau:
public class DocumentLibraryRepository<T> : IRepository<T>
where T : class, new()
{
public DocumentLibraryRepository(Guid listGuid, IEnumerable<IFieldToEntityPropertyMapper> fieldMappings)
{
...
}
...
}
Và IRepository trông giống như:
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();
}
Bạn có thiếu câu lệnh trả lại ở đó không? Bạn đã dán một bản sao đầy đủ của phương pháp đó chưa? –
Ngoài ra, tại sao bạn kiểm tra sự hiện diện của một hàm tạo parameterless khi rõ ràng bạn định gọi một constructor với các tham số? Nếu bạn có một hàm tạo parameterless, nó rất có thể sẽ là hàm tạo thứ 0 được trả về bởi 'GetConstructors', trong trường hợp gọi nó là * với tham số * sẽ thất bại. –
Có lỗi 'trả về mặc định (T)' nên ở cuối. – Bevan