lundi 26 décembre 2016

Invoke method from base class using reflection

I implemented generic repository pattern and unitofwork. I used basic patterns and they work great. In project I have requirement which says, every table has several fields which contains long, really long text, and user should have ability chose and open any of it. As each field named differently i decided to use power ov generics with reflection, to write method which resieves table name and field name and returns it. Generic method i wrote looks like this, it seems work properly

public string GetPropertyByName(int id, string property)
        {
            TEntity model =  this.Get(id);            
            var obj = model.GetType().GetProperty(property).GetValue(model, null);
            return obj != null ?  obj.ToString() : null;
        }

I have problem on invoking this method in business layer. I tried this:

public string GetHistory(string tableName, string fieldName, int id)
    {
        var prop = unitOfWork.GetType().GetProperty(tableName);
        MethodInfo method = prop.PropertyType.GetMethod("GetPropertyByName");
        var res = method.Invoke(prop, new object[] { id, fieldName });
        return (string)res;
    }

Which returns System.Reflection.TargetException. As I understood the problem is whith unitofwork implementation. In this pattern we create property:

public ICompanyRepo Company { get; private set; }

And then in constructor bind it with implementation:

Company = new CompanyRepo();

In my invoke method "prop" is type of interface (ICompanyRepo), but invoke's target should be interface implementation class, in this case "CompanyRepo". I could not find how to identify type of implementetion class, and solve this problem. Any help is appropriated





Aucun commentaire:

Enregistrer un commentaire