random thoughts and discussions on the things that interest me

InvalidOperationException: Dynamic operations can only be performed in homogenous AppDomain

Aaaah. Right. I didn’t expect that.

To set the scene, I’m writing a .NET 4.0 unit test in Visual Studio 2010 and using Microsoft Moles to test code that’s impossible to test (or something like that). My simplified unit test code can be found below.

using System.IO;
using System.IO.Moles;
using Microsoft.VisualStudio.TestTools.UnitTesting;

public classFileWrapperTest
    [TestMethod, HostType("Moles")]
    publicvoid TestMethod1()
        // arrange
        var fileWrapper = new FileWrapper();
        MFile.ExistsString = path => false;

        // act
        dynamic exists = fileWrapper.DoesExist(@"C:\temp\test.txt");

        // assert

    public classFileWrapper
        public bool DoesExist(string path)
            return File.Exists(path);

I’ve added a Moles assembly for mscorlib to the project and the following to AssemblyInfo.cs:

using Microsoft.Moles.Framework;
[assembly: MoledType(typeof(System.IO.File))]

I run the test and bang, InvalidOperationException: Dynamic operations can only be performed in homogenous AppDomain. Now – because of the lack of complexity in the simplified code – you may have spotted the cause. Why, you will be asking, has the boolean “exists” been declared as dynamic? Well… simply in order to illustrate the point (the test would work otherwise)! The DLR bombs if you attempt a dynamic operatioon, specifically System.Runtime.CompilerServices.CallSiteBinder .BindCore(CallSite site, Object[] args) with (thanks to Reflector) this little gem:

if (!AppDomain.CurrentDomain.IsHomogenous)
    throw Error.HomogenousAppDomainRequired();

Now, I know that the AppDomain should be homogenous when running in Full Trust following the overhall to CAS has had in .NET 4.0 (more here) and as that’s what I’m coding in why isn’t it? Well, it turns out that when you host an MS Test inside a Moles test host that the AppDomain that is created for the test is not homogenous. And that’s it. I’m not sure what to do next? I’ve posted in the forums and sent an email to Microsoft but not had a real reponse yet. I guess I’ll just need to be aware that I can’t use the DLR inside of a Moles test host.