Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silverlight: Cannot use reflection to GetValue of a field across XAPs?

I have a Silverlight application which has two different XAPs - an InitialXAP which is loaded statically by the HTML page and a DynamicXAP which is loaded from code within the initial XAP. The DynamicXAP is loaded with code similar to this:

var asm = LoadAssemblyFromXap(stream, "DLLName"); 
// LoadAssemblyFromXAP will load the DynamicXAP as a file stream, 
// unpack it and load DLLName as a dll. 
var controllerType = asm.GetType("ClassNameToInstantiate_InsideAsm");
var constructor = controllerType.GetConstructor(Type.EmptyTypes);
return constructor.Invoke(null);

I have a class which uses reflection (specifically FieldInfo.GetValue) to do data binding. This class is defined in the InitialXAP. If I try to use this class in the DynamicXAP, I get an error:

Message: Unhandled Error in Silverlight Application System.FieldAccessException: Class.In.DynamicXAP.Which.Uses.The.Reflection.Class.In.InitialXAP
   at System.Reflection.RtFieldInfo.PerformVisibilityCheckOnField(IntPtr field, Object target, IntPtr declaringType, FieldAttributes attr, UInt32 invocationFlags)
   at System.Reflection.RtFieldInfo.InternalGetValue(Object obj, Boolean doVisibilityCheck, Boolean doCheckConsistency)
   at System.Reflection.RtFieldInfo.InternalGetValue(Object obj, Boolean doVisibilityCheck)
   at System.Reflection.RtFieldInfo.GetValue(Object obj)

I can get around this error by creating a subclass of the class using reflection and overriding the method using reflection like so:

public class InitialXAP.ClassUsingReflection {

        public virtual object GetValue()
        {
            return fieldInfo.GetValue(parent);
        }
}

public class ClassUsingReflection : InitialXAP.ClassUsingReflection {

        public override object GetValue()
        {
            return fieldInfo.GetValue(parent);
        }
}

But I would prefer to avoid this duplication by allowing reflection from the InitialXAP in the DynamicXAP. Any ideas on what I can do?

like image 325
Rohith Avatar asked Jan 13 '10 05:01

Rohith


1 Answers

Although there is a learning curve, I would look at Silverlight MEF or Prism (both are together at last in the latest Prism 4 Beta). They both support dynamic loading of modules and enforce good patterns for reuse and separate/team development.

like image 147
Gone Coding Avatar answered Oct 16 '22 01:10

Gone Coding