title: Generics & Reflection - GenericArguments[0] violates the constraint of type
body: <p>I've been pulling my hair out for awhile on this one, essentially I'm trying to implement a generic repository factory, which is called as follows:</p>
  
  <pre><code>var resposFactory = new RepositoryFactory&lt;IRepository&lt;Document&gt;&gt;();
  </code></pre>
  
  <p>The repository factory looks like the following:</p>
  
  <pre><code>public class RepositoryFactory&lt;T&gt; : IRepositoryFactory&lt;T&gt;
  {
      public T GetRepository(Guid listGuid,
          IEnumerable&lt;FieldToEntityPropertyMapper&gt; 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 });
          }
      }
  }
  </code></pre>
  
  <p>When I try to call the GetRespository function the following line fails</p>
  
  <pre><code>Type newType = tempType.MakeGenericType(typeof(T));
  </code></pre>
  
  <p>The error I get is :</p>
  
  <blockquote>
    <p>ArgumentException - GenericArguments[0], 'Framework.Repositories.IRepository`1[Apps.Documents.Entities.PerpetualDocument]', on 'Framework.Repositories.DocumentLibraryRepository`1[T]' violates the constraint of type 'T'.</p>
  </blockquote>
  
  <p>Any ideas on what's going wrong here?</p>
  
  <p>EDIT:</p>
  
  <p>The implementation of the repository is as follows:</p>
  
  <pre><code>public class DocumentLibraryRepository&lt;T&gt; : IRepository&lt;T&gt;
                                                  where T : class, new()
  {
     public DocumentLibraryRepository(Guid listGuid, IEnumerable&lt;IFieldToEntityPropertyMapper&gt; fieldMappings)
     {
          ...
     }
  
     ...
  }
  </code></pre>
  
  <p>And the IRepository looks like:</p>
  
  <pre><code>public interface IRepository&lt;T&gt; where T : class
      {
          void Add(T entity);
          void Remove(T entity);
          void Update(T entity);
          T FindById(int entityId);
          IEnumerable&lt;T&gt; Find(string camlQuery);
          IEnumerable&lt;T&gt; All();
      }
  </code></pre>