[英]C# Reflection on UnitOfWork / Generic Repositories
这似乎是一个古老的问题,但是根本找不到我想要的东西。 这是我目前尝试执行的代码。
private async Task<T> HandleFileCreate<T>(Guid tableId, IFormFile file, DocumentType documentType)
where T : DocumentLibrary
{
// This works fine and gets the correct type
Type repoType = _unitOfWork.GetType().GetProperty(typeof(T).Name + "Repository").PropertyType;
// This works fine and creates an instance of my document
T document = (T)Activator.CreateInstance(typeof(T));
// Throws up error: "No parameterless constructor defined for this object."
object instance = Activator.CreateInstance(repoType);
// Throws up error: "Object does not match target type."
repoType.GetMethod("Create").Invoke(repoType, new object[] { document });
}
似乎有点麻烦,因为我无法为“创建”开票,没有CreateInstance似乎无法开票,在其中由于IoC而无法执行。
这确实很烦人,因为我已经在_unitOfWork中获得了一个实例化的属性,该属性直接与我的相关GenericRepository相关,我只是想不通如何访问它? 我什至不必重新实例化它。
Rader然后使用反射(总是一个坏主意)我建议做这样的事情
public static T Create<T>(IDocumentLibraryCreator<T> repo)// You can add you params here
where T: DocumentLibrary, new()
{
var newItem = new T();
repo.Create(newItem);
//Do your stuff here
return newItem;
}
public interface IDocumentLibraryCreator<T> where T : DocumentLibrary
{
Task Create(T document);
}
public abstract class DocumentLibrary
{
}
因为通过反射您将获得的只是运行时异常,而不是编译时异常。 无需反思。 您的存储库将需要实现IDocumentLibraryCreator<T>
接口,但是如果您以很好的方式完成了IRepository,则应该已经有了类似的东西。 如果需要在单个工作单元中完成工作,则需要传递在uof类中创建的实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.