简体   繁体   English

C#对UnitOfWork /通用存储库的反思

[英]C# Reflection on UnitOfWork / Generic Repositories

This seems like an age-old question, but simply can't find what I'm looking for. 这似乎是一个古老的问题,但是根本找不到我想要的东西。 Here's my current code with things I've tried. 这是我目前尝试执行的代码。

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 });
        }

It seems a bit chicken and egg because I can't invoice "Create" it seems without the CreateInstance, in which I can't do because of IoC. 似乎有点麻烦,因为我无法为“创建”开票,没有CreateInstance似乎无法开票,在其中由于IoC而无法执行。

This is really annoying because I've already got an instantiated property in _unitOfWork which relates directly to my relevant GenericRepository, I just can't figure out how to access it? 这确实很烦人,因为我已经在_unitOfWork中获得了一个实例化的属性,该属性直接与我的相关GenericRepository相关,我只是想不通如何访问它? I shouldn't even have to re-instantiate it. 我什至不必重新实例化它。

Rader then using reflection(Always a bad idea) I would recommend doing something like this 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
        {

        }

Because all you will get with reflection is runtime exceptions and not compile time exceptions. 因为通过反射您将获得的只是运行时异常,而不是编译时异常。 No need for reflection. 无需反思。 Your repo will need to implement IDocumentLibraryCreator<T> interface but if you did IRepository in a good way you should have something like this already. 您的存储库将需要实现IDocumentLibraryCreator<T>接口,但是如果您以很好的方式完成了IRepository,则应该已经有了类似的东西。 You will need to pass the instance created in the uof class if you need the work to be done in a single Unite of work. 如果需要在单个工作单元中完成工作,则需要传递在uof类中创建的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM