I have some classes like this:
public class Customer
{ }
public interface IRepository
{ }
public class Repository<T> : IRepository
{ }
public class CustomerRepository<Customer>
{ }
Then, as per the answer to this question I can use reflection to get a list of types referenced by generics for each of my *Repository:
What I want to end up with is a Dictionary<Type, IRepository>
So far, I have this:
Dictionary<Type, IRepository> myRepositories = Assembly.GetAssembly(typeof(Repository<>))
.GetTypes()
.Where(typeof(IImporter).IsAssignableFrom)
.Where(x => x.BaseType != null && x.BaseType.GetGenericArguments().FirstOrDefault() != null)
.Select(
x =>
new { Key = x.BaseType != null ? x.BaseType.GetGenericArguments().FirstOrDefault() : null, Type = (IRepository)x })
.ToDictionary(x => x.Key, x => x.Type);
However, it doesn’t like my cast (IRepository)x
I get the following error:
Unable to cast object of type ‘System.RuntimeType’ to type ‘My.Namespace.IRepository’.
You cannot cast
(IRepository) typewith type isTypeclass,you can use
Activator.CreateInstanceto create objectCustomerRepository, you also don’t need to useSelect, instead, useToDictionarydirectly, the code below: