AppDomain and CreateInstanceAndUnwrap: cast fails
Description
From a test project "A" that uses at least a DeploymentItem (so there is an "Out" directory where "A" and its dependencies are copied), I create an AppDomain "B", then I call CreateInstanceAndUnwrap to instantiate a class "C" in the AppDomain "B".
If class "C" is in assembly "A" itself, "C" is loaded from the copy of "A" that is in the Debug (or Release) directory and not from the "Out" directory as any other assembly in this situation. So the proxy of "C" returned from CreateInstanceAndUnwrap cannot be cast to its original type.
It used to work with old Microsoft.VisualStudio.QualityTools.UnitTestFramework.
Steps to reproduce
CSPROJ:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net472</TargetFramework>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<AutoGenerateBindingRedirects>false</AutoGenerateBindingRedirects>
<RootNamespace>MyCompany.MyTestPrj</RootNamespace>
<AssemblyName>MyCompany.MyTestPrj</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<DebugSymbols>true</DebugSymbols>
<Prefer32Bit>false</Prefer32Bit>
<PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<DebugType>pdbonly</DebugType>
<DebugSymbols>true</DebugSymbols>
<Prefer32Bit>false</Prefer32Bit>
<PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<Content Include="TextFile1.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.8.0" />
<PackageReference Include="MSTest.TestAdapter" Version="1.3.2" />
<PackageReference Include="MSTest.TestFramework" Version="1.3.2" />
</ItemGroup>
</Project>
C# code:
namespace MyCompany.MyTestPrj
{
[DeploymentItem("TextFile1.txt")]
[TestClass]
public class TestClass1
{
[TestMethod]
public void TestMethod1()
{
var setupInfo = AppDomain.CurrentDomain.SetupInformation;
AppDomain domain = AppDomain.CreateDomain("MY_" + Guid.NewGuid(), null, setupInfo);
Type type = typeof(SpecialTestCode);
Console.WriteLine($"Typeof, Location: {type.Assembly.Location}");
object proxy = domain.CreateInstanceAndUnwrap(
type.Assembly.FullName, type.FullName);
Console.WriteLine($"proxy, Location: {proxy.GetType().Assembly.Location}");
SpecialTestCode codeInOtherDomain = (SpecialTestCode)proxy;
codeInOtherDomain.SomeMethod();
}
}
public class SpecialTestCode : MarshalByRefObject
{
public SpecialTestCode()
{
// do something
}
public override object InitializeLifetimeService()
{
return null;
}
public void SomeMethod()
{
// Do something
}
}
}
Expected behavior
With Microsoft.VisualStudio.QualityTools.UnitTestFramework, both appdomains load the assembly from the "Out" directory:
Typeof, Location: C:\temp\MyTestPrj\TestResults\Deploy_myusername 2018-11-29 13_29_04\Out\MyCompany.MyTestPrj.dll
proxy, Location: C:\temp\MyTestPrj\TestResults\Deploy_myusername 2018-11-29 13_29_04\Out\MyCompany.MyTestPrj.dll
The proxy returned from CreateInstanceAndUnwrap can be cast to its original type
Actual behavior
After migrating to MsTest.TestFramework, two copies of the assembly are loaded in the process:
Typeof, Location: C:\temp\MyTestPrj\TestResults\Deploy_myusername 2018-11-29 13_31_08\Out\MyCompany.MyTestPrj.dll
proxy, Location: C:\temp\MyTestPrj\MyTestPrj\bin\Debug\MyCompany.MyTestPrj.dll
From different binding contexts, as FUSLOGVW says:
WRN: The same assembly was loaded into multiple contexts of an application domain:
WRN: Context: Default | Domain ID: 4 | Assembly Name: MyCompany.MyTestPrj, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
WRN: Context: LoadFrom | Domain ID: 4 | Assembly Name: MyCompany.MyTestPrj, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
Cast fails: "System.InvalidCastException: Unable to cast transparent proxy to type 'MyCompany.MyTestPrj.SpecialTestCode"
Environment
Reproduced on Windows 10 (Version 10.0.15063) with Visual Studio 2017 (15.8.7) and MSTest.TestFramework/TestAdapter 1.3.2 (but the problem also occurs with version 1.4 of TestFramework/TestAdapter and version 16.0.0-preview-20181128-01 of Microsoft.NET.Test.Sdk).
As I said in the question I posted on StackOverflow, after reading articles about similar problems I tried to change the way I create the appdomain and/or the way I call CreateInstanceAndUnwrap and/or to add a custom resolver, but the problem still occurs. Removing every instance of DeploymentItem from the assembly works because in this way there is only one copy of my DLL (but it means changing a huge number of existing tests). Using dynamic does NOT work ("An unexpected exception occurred while binding a dynamic operation").
@PablitoPaul: While debugging we saw that MyCompany.MyTestPrj.dll is indeed getting loaded from \out location in MY_* appdomain but still when you do proxy.GetType().Assembly.Location, it points to bin\Debug. We are trying to follow up with CLR teams to investigate this on our end but these appdomains can be tricky.
Owing to the confusing nature of appdomains and assembly loading, all of this stuffed has been dropped .net core world.
@jayaranigarg Thank you for your reply! Yes I know AppDomains are not in .NET Core, in fact, in the long run, we are planning to support also .NET Core and avoid using them. But at the moment our product must target .NET Framework only, and we need AppDomains desperately. I'll wait for the results of your investigation...
@PablitoPaul : Unfortunately there has not been much information we could figure out from the investigations. Best bet would be to take community help on stack overflow.
We ran into the same problem after migrating to MSTest 1.4.0. In our case, the tests are fine locally but failed on an Azure DevOps build agent (nothing changed to the build definition and it was working before the migration). Many of our existing unit tests start to fail, especially those involved MEF. This problem should get more attention. I hope MS will have an update soon to address the problem.
@freebird8x We understand your concern, but the core issue here is not being handled appropriately in CLR layer itself. However to help us investigate your scenario, can you please provide a sample MEF project, where you are facing this issue.