Search code examples
c#reflectionmvvmcrossportable-class-library

Reflection API missing in Portable Class Library Profile259


I had the following code working fine in a PCL with TargetFrameworkVersion of 4.0 and TargetFrameworkProfile of Profile104.

 public class AppCapabilitiesRepository : IAppCapabilityRepository
    {
        private readonly Type _typeOfAppCapability = typeof (IAppCapability);

        public IList<IAppCapability> GetCapabilities()
        {
            var capabilities = Assembly.GetExecutingAssembly().GetTypes().Where(IsAppCapability).ToArray();
            var viewModels = capabilities.Select(capability => ((IAppCapability)Activator.CreateInstance(capability)))
                .Where(c => c.IsActive)
                .OrderBy(c => c.Popularity).ToList();
            return viewModels;
        }

        private bool IsAppCapability(Type type)
        {
            return _typeOfAppCapability.IsAssignableFrom(type) && !type.IsAbstract && !type.IsInterface;
        }
    }

After upgrading the project to TargetFrameworkVersion of 4.5 and TargetFrameworkProfile of Profile259, these reflection APIs no longer can be found:

Assembly.GetExecutingAssembly, Type.IsAbstract and Type.IsInterface.

This solution is also using MvvmCross 3.5.1 if this matters.

What do I do now?


Solution

  • Thanks to Stuart for the tip. API changes I needed to do are as follows:

    Assembly.GetExecutingAssembly => this.GetType().GetTypeInfo().Assembly
    Type.IsAbstract => TypeInfo.IsAbstract where TypeInfo.GetTypeInfo()
    Type.IsInterface => TypeInfo.IsInterface where TypeInfo = Type.GetTypeInfo()
    

    Modified code is as follows:

      public class AppCapabilitiesRepository : IAppCapabilityRepository
        {
            private readonly Type _typeOfAppCapability = typeof (IAppCapability);
    
            public IList<IAppCapability> GetCapabilities()
            {
                var capabilities =  GetType().GetTypeInfo().Assembly.GetTypes().Where(IsAppCapability).ToArray();
                var viewModels = capabilities.Select(capability => ((IAppCapability)Activator.CreateInstance(capability)))
                    .Where(c => c.IsActive)
                    .OrderBy(c => c.Popularity).ToList();
                return viewModels;
            }
    
            private bool IsAppCapability(Type type)
            {
                var typeInfo = type.GetTypeInfo();
                return _typeOfAppCapability.IsAssignableFrom(type) && !typeInfo.IsAbstract && !typeInfo.IsInterface;
            }
        }
    

    Some laws are being violated here but .....

    Hope this helps others.