Skip to content

Call WCF client generated from Visual Studio from different AssemblyLoadContext causes exception #5688

Open
@mcortellino

Description

@mcortellino

Describe the bug
When call the same WCF client generated from VS2022 (Add Service Reference) loaded by reflection
through 2 different AssemblyLoadContext the second call causes an InvalidCastException 'Unable to cast object of type 'generatedProxy_2' to type 'ServiceReference3.Service1Soap'.

To Reproduce
Steps to reproduce the behavior:
TestWcfClient.zip

AssemblyLoadContext lc1 = new AssemblyLoadContext("alc1");
 string clientAssembly1 = Path.GetFullPath("..\\..\\..\\..\\WcfClient\\bin\\Debug\\net8.0\\WcfClient.dll");
 var assembly1 = lc1.LoadFromAssemblyPath(clientAssembly1);
 var helper1 = assembly1.GetTypes().FirstOrDefault(x => x.FullName.Contains("WcfHelper"));
 var instance1 = (IWcfHelper)Activator.CreateInstance(helper1);
 string result1 = instance1.CallWcf();
 Console.WriteLine("Result 1: " + result1);


 AssemblyLoadContext lc2 = new AssemblyLoadContext("alc2");
 string clientAssembly2 = Path.GetFullPath("..\\..\\..\\..\\WcfClient\\bin\\Debug\\net8.0\\WcfClient.dll");
 var assembly2 = lc2.LoadFromAssemblyPath(clientAssembly2);
 var helper2 = assembly2.GetTypes().FirstOrDefault(x => x.FullName.Contains("WcfHelper"));
 var instance2 = (IWcfHelper)Activator.CreateInstance(helper2);
 string result2 = instance2.CallWcf(); // <-- throw InvalidCastException
 Console.WriteLine("Result 2: " + result2);

Check the attached sample project for the full code.

Expected behavior
The WCF client should be called from differents AssemblyLoadContext without exception.

Additional context
Framework: .NET8
VisualStudio 2022 Version 17.11.5

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions