microsoft / winforms-designer-extensibility

MIT License
56 stars 13 forks source link

Different AssemblyLoadContext for System.CodeDom types #19

Open drolevar opened 1 year ago

drolevar commented 1 year ago

I'm trying to port a .NET Framework control to .NET 5 which has a custom CodeDomSerializer.

However I'm facing a very strange issue that all the static types are loaded as a part of "Default" context. All the dynamic types though are loaded as a part of "UserAssemblyLoadContext".

So if I write the following:

CodeDomSerializer baseSerializer = (CodeDomSerializer)manager.GetSerializer(typeof(ControlBase).BaseType, typeof(CodeDomSerializer));
var codeObject = baseSerializer.Serialize(manager, value);

And then

var statements = (CodeStatementCollection)codeObject;

I can also get the following exception:

[A]System.CodeDom.CodeStatementCollection cannot be cast to [B]System.CodeDom.CodeStatementCollection.
Type A originates from 'System.CodeDom, Version=7.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' in the context 'Default' at location 'C:\Users\<username>\.nuget\packages\system.codedom\7.0.0\lib\net6.0\System.CodeDom.dll'.
Type B originates from 'System.CodeDom, Version=7.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' in the context 'Default' at location 'C:\Users\<username>\.nuget\packages\system.codedom\7.0.0\lib\net6.0\System.CodeDom.dll'

Do you have an idea how to resolve the issue?

KlausLoeffelmann commented 12 months ago

In .NET the "same" assembly can be loaded twice into the context, just because the file origin is different. Actually, then the assembly is also considered to be a different version. But this doesn't seem to be the case, here.

Could you try to see, if in the debugger at the point where the assembly is about to be used (the types to be cast), the location shown in the debugger of the context is in fact what's been stated here? And then later, if also the debugger states, that both assemblies came from the same origin?

Maybe @terrajobst has an idea here? Also @Shyam-Gupta FYI.

terrajobst commented 9 months ago

@jaredpar likely knows much more than me in this space

jaredpar commented 9 months ago

Does any of your code use Assembly.LoadFrom? That will result in the Assembly being loaded in the Default instead of Current context. Seen that cause this kind of confusion before.