Monday, December 10, 2012

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

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?

Answers & Comments...

Answer: 1

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.

by : HiTech Magichttp://stackoverflow.com/users/201078

Answer: 2

InitialXAP.ClassUsingReflection...

Note the duplicate isn't part of the inital xap namespace (ClassUsingReflection), and may be imported. Notice GetVisible - as in not visible to Dynamic xap... Just leave the duplicate (take away base class obviously) and try.

by : Not applicablehttp://stackoverflow.com/users/481005




No comments:

Post a Comment

Send us your comment related to the topic mentioned on the blog