Reflection and XMLSerialization

T

Todd

I have a C# App that allows users (other programmers) to load
assemblies dynamically and invoke methods. The app itself uses a
generic tools assembly (Tools.dll). If the user then uses the app to
load the tools.dll assembly, any XML Serialization eventually called
through Method.Invoke fails. I have verified this by simply removing
Tools.Dll from the application and XML Serialization in the
dynamically loaded tools.dll succeeds. The exception message is
"Specified cast has failed." in the dynamically generatic XML
serialization assembly.

I expected the Assembly.LoadFrom might fail because the assembly was
already loaded - however, tools.dll isn't loaded yet because it hasn't
been used at that point in the program flow. I am confused as to why
a reference to a DLL that isn't even loaded yet would cause
XMLSerialization to fail. The pseudo code is as follows:

// (Main app includes a reference to tools.dll - which is never loaded
until this call:)

Assembly assembly = null;
try
{
assembly = Assembly.LoadFrom( "tools.dll" );
}
catch( BadImageFormatException )
{
// a regular DLL not an assembly - so skip it
continue;
}

// blah blah blah - get the method the user wants to invoke from the
assembly

methodInfo.Invoke( assembly, null );

// if the method above calls Serialize or Deserialize, and exception
is thrown. Simply removing tools.dll from the references list solves
the problem - obviously however I need to use the tools provided in
tools.dll so i can't do that. Somehow the reference to the assembly
changes something however, I am lost and my google / usenet searches
have failed me this time.

Thanks,
Todd
 
B

boneil

Hello Todd,

Using LoadFrom cause the types loaded from the DLL to be isolated. If you
already have a reference to the type in the application and then load the
same types into the AppDomain then you can have types that can't be cast
to what looks like the same type because of the isolation.

Check out this article on gotdotnet... http://www.gotdotnet.com/team/clr/LoadFromIsolation.aspx


It give a pretty good summary of how loaded assemblies are isolated and will
probably help you understand what is going on.

-Brian
 
T

Todd

I had done some further tests and came to a similar conclusion, but
the official article helps explain the details. Thanks!

Todd
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top