开发者

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

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 goi开发者_如何学Cng to work?

Thank you!


You target the 2.0 so it is the one loaded in memory... they you ask it to load a 4.0 image... it can't work you need to spin a new Runtime instance of the correct version if you want to do that.

The only way to do that may be to Host a second CLR inside your process like explained in Is it possible to host the CLR in a C program? witch became possible with .Net 4.0.


I would be inclined to suspect that the version 2 of the .NET runtime has no clue nor understanding of .NET 4. By the sound and nature of your question, you are dealing with it in the reverse....Have you tried compiling and targetting for .NET 4 to load the .NET 2 runtime library...I would not think it is possible to inter-mix different versions of compiled code (one for .NET 4 and the other for .NET 2) in the same process...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜