I'd suggest returning the collection of repository types instead of the names and just displaying the names in the UI:
public static IEnumerable<Type> GetAvailableRepositoryClasses()
{
return Assembly.GetExecutingAssembly().GetTypes()
.Where(t => t.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof (IRepository<>)));
}
Then when a user selects the source you can do:
object repository = Activator.CreateInstance(selectedType);
This method requires each repository to have a default constructor.
Activator.CreateInstance
return an object, and you can't cast it to your IRepository<T>
interface unless you know the generic type T
you're expecting. The best solution is probably to create a non-generic IRepository
interface which your repository classes also implement:
public interface IRepository
{
IList<object> GetAll();
}
Now you can cast your created repositories to IRepository
:
IRepository repository = (IRepository)Activator.CreateInstance(selectedType);
you might to create a repository base class which implements both:
public abstract class RepositoryBase<T> : IRepository<T>, IRepository
{
public abstract IList<T> GetAll();
IList<object> IRepository.GetAll()
{
return this.GetAll().Cast<object>().ToList();
}
}