Is it possible to load an assembly targeting a different .NET runtime version in a new app domain?

Posted by Notre on Stack Overflow See other posts from Stack Overflow or by Notre
Published on 2010-03-26T17:27:23Z Indexed on 2010/03/26 17:43 UTC
Read the original article Hit count: 319

Hello,

I've an application that is based on .NET 2 runtime. I want to add a little bit of support for .NET 4 but don't want to (in the short term), convert the whole application (which is very large) to target .NET 4.

I tried the 'obvious' approach of creating an application .config file, having this:

<startup useLegacyV2RuntimeActivationPolicy="true">
  <supportedRuntime version="v4.0" />
</startup>

but I ran into some problems that I noted here.

I got the idea of creating a separate app domain. To test it, I created a WinForm project targeting .NET 2. I then created a class library targeting .NET 4. In my WinForm project, I added the following code:

        AppDomainSetup setup = new AppDomainSetup();
        setup.ApplicationBase = "path to .NET 4 assembly";
        setup.ConfigurationFile = System.Environment.CurrentDirectory + 
          "\\DotNet4AppDomain.exe.config";

        // Set up the Evidence
        Evidence baseEvidence = AppDomain.CurrentDomain.Evidence;
        Evidence evidence = new Evidence(baseEvidence);

        // Create the AppDomain      
        AppDomain dotNet4AppDomain = AppDomain.CreateDomain("DotNet4AppDomain", evidence, setup);
        try
        {
            Assembly doNet4Assembly = dotNet4AppDomain.Load(
               new AssemblyName("MyDotNet4Assembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=66f0dac1b575e793"));
            MessageBox.Show(doNet4Assembly.FullName);
        }
        finally
        {
            AppDomain.Unload(dotNet4AppDomain);
        }

My DotNet4AppDomain.exe.config file looks like this:

<startup useLegacyV2RuntimeActivationPolicy="true">
  <supportedRuntime version="v4.0" />
</startup>

Unfortunately, this throws the BadImageFormatException when dotNet4AppDomain.Load is executed. Am I doing something wrong in my code, or is what I'm trying to do just not going to work?

Thank you!

© Stack Overflow or respective owner

Related posts about appdomain

Related posts about runtime