Silverlight: Can't use reflection for GetValue fields in XAP?

I have a Silverlight application in which there are two different XAPs - InitialXAP, which is statically placed on the HTML page and DynamicXAP, which is loaded from the code in the initial XAP. DynamicXAP is loaded with code like 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 that uses reflection (specifically FieldInfo.GetValue) to perform data binding. This class is defined in InitialXAP. If I try to use this class in 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 this:

 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 InitialXAP in DynamicXAP. Any ideas on what I can do?

+6
reflection silverlight
source share
2 answers

Although there is a learning curve, I would look at Silverlight MEF or Prism (both together, finally, in the latest Prism 4 Beta ). They support dynamic module loading and provide good templates for reuse and separate / team development.

+1
source share

InitialXAP.ClassUsingReflection ...

Note that the duplicate is not part of the inital xap ( ClassUsingReflection ) ClassUsingReflection and can be imported. Pay attention to GetVisible - as invisible to Dynamic xap ... Just leave a duplicate (obviously, take away the base class) and try.

0
source share

All Articles