Điều này sẽ trả về tất cả các loại kế thừa một lớp cơ sở chung. Không phải tất cả các loại thừa hưởng giao diện chung.
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;
Điều này sẽ trả về tất cả các loại, bao gồm giao diện, tóm tắt và loại bê tông có loại mở chung trong chuỗi kế thừa của nó.
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;
}
Phương pháp thứ hai này sẽ tìm ConcreteUserRepo và IUserRepository trong ví dụ này:
public interface ConcreteUserRepo : IUserRepository
{}
public interface IUserRepository : IRepository<User>
{}
public interface IRepository<User>
{}
public class User
{}
Nguồn
2011-12-27 14:07:58
Có, nhưng bạn sẽ chỉ nhận được concreterepo và irepo khi nó ở trong cùng một cụm. Nhưng điều này là hoàn toàn ok. – Rookian
Tốt bắt! Chúng tôi phải cẩn thận để tải tất cả các hội đồng phụ thuộc, không chỉ quét hiện đang được nạp. Đây là một SO về tải tất cả các hội đồng: http://stackoverflow.com/questions/2384592/c-net-is-there-a-way-to-force-all-referenced-assemblies-to-be-loaded-into- –
Loại (IRepository <>) chỉ hoạt động nếu loại chung có một tham số chung duy nhất. Bất kỳ ý tưởng nào cho các loại có nhiều thông số loại chung? – dotnetguy