vendredi 17 février 2017

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.

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? I shouldn't even have to re-instantiate it.





Aucun commentaire:

Enregistrer un commentaire