我目前的代码如下所示:
var cacheWork = new UnitOfWork();
Log.Info("Caching Cable Entity");
cacheWork.GetRepository<CableEntity>().All();
Log.Info("Caching CablePart Entity");
cacheWork.GetRepository<CablePartEntity>().All();
Log.Info("Caching CableType Entity");
cacheWork.GetRepository<CableTypeEntity>().All();
Log.Info("Caching Country Entity");
cacheWork.GetRepository<CountryEntity>().All();
Log.Info("Caching Filesystem Entity");
cacheWork.GetRepository<FilesystemEntity>().All();
Log.Info("Caching Host Entity");
cacheWork.GetRepository<HostEntity>().All();
Log.Info("Caching Location Entity");
cacheWork.GetRepository<LocationEntity>().All();
Log.Info("Caching NodeCable Entity");
cacheWork.GetRepository<NodeCableEntity>().All();
Log.Info("Caching Node Entity");
cacheWork.GetRepository<NodeEntity>().All();
Log.Info("Caching Person Entity");
cacheWork.GetRepository<PersonEntity>().All();
Log.Info("Caching Tier Entity");
cacheWork.GetRepository<TierEntity>().All();
Log.Info("Caching User Entity");
cacheWork.GetRepository<UserEntity>().All();
cacheWork.Dispose();
我想要的是摆脱每个类的显式声明类型。我能够检索所有类型并将其作为列表返回。
我现在想要的是做这样的事情:
var ns = typeof(T).Namespace;
var types = typeof(T).Assembly.GetExportedTypes()
.Where(t => t.Namespace == ns);
var cacheWork = new UnitOfWork();
foreach (Type t in types)
cacheWork.GetRepository<t>().All();
cacheWork.Dispose();
所以我已经知道这种语法不起作用,但我认为它必须通过例如反射来实现这一点。有谁可以帮我这个?
修改
从已经回答的SO问题中我提出了以下解决方案:
var ns = typeof(BaseEntity).Namespace;
var types = typeof(BaseEntity).Assembly.GetExportedTypes()
.Where(t => t.Namespace == ns);
var cacheWork = new UnitOfWork();
types.ForEach(x =>
{
Log.Info("Caching " + x.Name + "...");
MethodInfo repoMethod = typeof (UnitOfWork).GetMethod("GetRepository");
MethodInfo generic = repoMethod.MakeGenericMethod(x);
var repository = generic.Invoke(cacheWork, null);
MethodInfo getAllMethod = repository.GetType().GetMethod("All");
getAllMethod.Invoke(repository, null);
});
cacheWork.Dispose();