泛型和反射 - GenericArguments [0]违反了类型的约束

Bev*_*van 11 .net c# generics reflection factory-pattern

我已经把头发拉了一段时间了,基本上我正在尝试实现一个通用的存储库工厂,调用如下:

var resposFactory = new RepositoryFactory<IRepository<Document>>();
Run Code Online (Sandbox Code Playgroud)

存储库工厂如下所示:

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 });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试调用GetRespository函数时,以下行失败

Type newType = tempType.MakeGenericType(typeof(T));
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:

ArgumentException - GenericArguments [0],'Framework.Repositories.IRepository`1 [Apps.Documents.Entities.PerpetualDocument]','Framework.Repositories.DocumentLibraryRepository`1 [T]'违反了类型'T'的约束.

关于这里出了什么问题的任何想法?

编辑:

存储库的实现如下:

public class DocumentLibraryRepository<T> : IRepository<T>
                                                where T : class, new()
{
   public DocumentLibraryRepository(Guid listGuid, IEnumerable<IFieldToEntityPropertyMapper> fieldMappings)
   {
        ...
   }

   ...
}
Run Code Online (Sandbox Code Playgroud)

而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();
    }
Run Code Online (Sandbox Code Playgroud)

Dan*_*rth 8

您的代码尝试创建DocumentLibraryRepository<IRepository<Document>>而不是的实例DocumentLibraryRepository<Document>.

您想要使用此代码:

var genericArgument = typeof(T).GetGenericArguments().FirstOrDefault();
if (tempType != null && genericArgument != null)
{
    Type newType = tempType.MakeGenericType(genericArgument);
Run Code Online (Sandbox Code Playgroud)