I am pulling my hair out a bit on this, in fact, I'm trying to implement a common factory repository, which is invoked as follows:
var resposFactory = new RepositoryFactory<IRepository<Document>>();
The factory repository is as follows:
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 }); } } }
When I try to call the GetRespository function, the next line fails
Type newType = tempType.MakeGenericType(typeof(T));
The error I get is:
ArgumentException - GenericArguments [0], 'Framework.Repositories.IRepository`1 [Apps.Documents.Entities.PerpetualDocument]', in 'Framework.Repositories.DocumentLibraryRepository`1 [T]' violates the restriction of type 'T'.
Any ideas on what's going wrong here?
EDIT:
The storage implementation is as follows:
public class DocumentLibraryRepository<T> : IRepository<T> where T : class, new() { public DocumentLibraryRepository(Guid listGuid, IEnumerable<IFieldToEntityPropertyMapper> fieldMappings) { ... } ... }
And the IRepository looks like this:
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(); }
Bevan
source share