Search code examples
c#wcfreflectionautomappersystem.reflection

Reflection, get collection of objects and convert these to desired object type


So.. I have some WCF services, and these wcf services are called with reflection. They return arrays with objects that are different for each service that gets called.

My mission is to get these objects and map them to objects that i have in my BusinessObjects. They are defined by the T.

    public virtual IQueryable<T> GetAll()
    {
        //Methods retreives an array of objects.
        var blah = _getAllFromWcf.Invoke(_rawServiceObject, new object[] {});
        //Says that this is an array
        var blahsType = blah.GetType();
        //This is the type of object in the array
        var blahsElementType = blahsType.GetElementType();
        //This is where i want to convert the element in the array to the type T so that i can return it in the IQueryable<T>
        blah.MapCollection<'The type of element in blah', T>();

        return null;
    }

The blah.MapCollection<> is an extension method i have made that uses AutoMapper and converts elements in lists.

The MapCollection will of course not work right now, because it does not understand that blah is an array, and 'The type of element in blah' is not working, because i dont know the type of the object at this time....

Anyone has any guidance?


Solution

  • I ended up doing it like this.. if you have comments on it, or just have a better way of doing it, please feel free to comment :)

        public virtual IQueryable<T> GetAll()
        {
            //Methods retreives an array of objects.
            var collectionFromWcfService = _getAllFromWcf.Invoke(_rawServiceObject, new object[] {});
            //Says that this is an array
            var typeOfArray = collectionFromWcfService.GetType();
            //This is the type of object in the array
            var elementTypeInArray = typeOfArray.GetElementType();
    
            MethodInfo method = typeof(Extensions).GetMethod("MapCollectionWithoutExtension");
            MethodInfo generic = method.MakeGenericMethod(elementTypeInArray,typeof(T));
    
            var convertedListOfObjects = (List<T>)generic.Invoke(this, new []{ collectionFromWcfService });
    
            return convertedListOfObjects.AsQueryable(); 
        }
    

    With this solution i have hidden away the AutoMapper implementation and can now do the conversion by another tool, or manually if i need it at a later point in time.