MATLAB: Can the Assembly not be found when deserializing a .NET object in MATLAB 7.10 (R2010a)

MATLAB

I have two .NET Assemblies:
1. myAssembly1: implements a class myClass1.
2. myAssembly2: implements a class myClass2 which can serialize, deserialize and return objects of type myClass1.
In MATLAB I use NET.addAssembly to load both myAssembly1 and myAssembly2. Then when I try to use myClass2 to deserialize and return an object of type myClass1, I receive the following error:
??? Message: Unable to find assembly 'myAssembly1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
Source: mscorlib
HelpLink:
So even though myAssembly1 is already loaded into my AppDomain, MATLAB claims that it cannot find it.

Best Answer

Please note that the behavior described above is not a limitation of MATLAB. It is in fact expected behavior of the .NET framework.
By default when deserializing an object, the .NET Framework will only look for the required Assembly in the "EXE directory"; it will not even look for already loaded Assemblies.
To make the deserialization work, you will thus need to either:
1. Place myAssembly1.dll in the $MATLABROOT\bin\[win32|win64] directory, or
2. Implement your own ResolveEventHandler for the AppDomain.CurrentDomain.AssemblyResolve event in myAssembly2. So for example in the constructor of myClass2 add:
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
To register your own ResolveEventHandler called CurrentDomain_AssemblyResolve. This CurrentDomain_AssemblyResolve could look like:
System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
System.Reflection.Assembly ayResult = null;
string sShortAssemblyName = args.Name.Split(',')[0];
System.Reflection.Assembly[] ayAssemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (System.Reflection.Assembly ayAssembly in ayAssemblies)
{
if (sShortAssemblyName == ayAssembly.FullName.Split(',')[0])
{
ayResult = ayAssembly;
break;
}
}
return ayResult;
}
This particular ResolveEventHandler will allow you to use already loaded Assemblies when deserializing objects.