これは、汎用基本クラスを継承するすべての型を返します。ジェネリックインターフェイスを継承するすべての型ではありません。
var AllTypesOfIRepository = from x in Assembly.GetAssembly(typeof(AnyTypeInTargetAssembly)).GetTypes()
let y = x.BaseType
where !x.IsAbstract && !x.IsInterface &&
y != null && y.IsGenericType &&
y.GetGenericTypeDefinition() == typeof(IRepository<>)
select x;
これは、継承チェーンに開いたジェネリック型を持つインターフェイス、抄録、具体的な型を含むすべての型を返します。
public static IEnumerable<Type> GetAllTypesImplementingOpenGenericType(Type openGenericType, Assembly assembly)
{
return from x in assembly.GetTypes()
from z in x.GetInterfaces()
let y = x.BaseType
where
(y != null && y.IsGenericType &&
openGenericType.IsAssignableFrom(y.GetGenericTypeDefinition())) ||
(z.IsGenericType &&
openGenericType.IsAssignableFrom(z.GetGenericTypeDefinition()))
select x;
}
この第二の方法は、この例ではConcreteUserRepoとIUserRepositoryがあります:あなたが試みることができる
public interface ConcreteUserRepo : IUserRepository
{}
public interface IUserRepository : IRepository<User>
{}
public interface IRepository<User>
{}
public class User
{}
はい、ただし、同じアセンブリ内にある場合は、concreterepoとirepoのみを取得します。しかし、これは絶対に大丈夫です。 – Rookian
良いキャッチ!現在ロードされているスキャンだけでなく、すべての依存アセンブリをロードするように注意する必要があります。ここではすべてのアセンブリをロードする方法について説明します:http://stackoverflow.com/questions/2384592/c-net-is-there-a-way-to-force-all-referenced-assemblies-to-be-loaded-into- –
タイプ(IRepository <>)は、汎用タイプに1つの汎用パラメータがある場合にのみ機能します。複数のジェネリック型パラメータを持つタイプのアイデアですか? – dotnetguy