dotnet / dotnet/wcf

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

Open
#5,688 2 comments 0 reactions 0 assignees View on GitHub
triaged
Dominant language
C#
Stars
1.8k
Forks
576
Avg merge
6d 9h
Merged PRs (30d)
2

Description

**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](https://github.com/user-attachments/files/17749592/TestWcfClient.zip)

```c#
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

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.