Can I load an assembly for a different version of the .NET runtime in a new application domain?

I have an application based on the .NET 2 runtime. I want to add a bit of support for .NET 4, but I do not want (in the short term) to convert the entire application (which is very large) to the target .NET 4.

I tried the "obvious" approach to creating an .config file for an application having the following:

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

but I ran into some problems that I noted here .

I had an idea to create a separate application domain. To test it, I created a WinForm project oriented to .NET 2. Then I created a class library oriented to .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 :

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

, BadImageFormatException, dotNet4AppDomain.Load. - , , , ?

!

+3
2

2.0, , ... 4,0-... , Runtime , .

, CLR , CLR C? .Net 4.0.

+1

, 2 .NET .NET 4. .... .NET 4 .NET 2... , ( .NET 4, .NET 2) ...

0

Source: https://habr.com/ru/post/1738698/


All Articles