私は本質的に次のように呼び出される汎用リポジトリファクトリを実装しようとしています。Generics&Reflection - GenericArguments [0]はタイプ
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が - Framework.Repositories.DocumentLibraryRepository`1」に関するGenericArguments [0]、 'Framework.Repositories.IRepository`1 [Apps.Documents.Entities.PerpetualDocument]'、 [T] 'は型' T 'の制約に違反します。
ここで何が問題になっているかについてのアイデアはありますか?
EDIT:
次のようにリポジトリの実装は次のとおりです。
public class DocumentLibraryRepository<T> : IRepository<T>
where T : class, new()
{
public DocumentLibraryRepository(Guid listGuid, IEnumerable<IFieldToEntityPropertyMapper> fieldMappings)
{
...
}
...
}
などIRepositoryに見える:あなたのコードはDocumentLibraryRepository<IRepository<Document>>
の代わりのインスタンスを作成しようと
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番目のコンストラクタになる可能性が最も高くなります。この場合、* with *パラメータを呼び出すと失敗します。 –
はいごめんなさい。「デフォルトを返す(T)」は最後にする必要があります。 – Bevan