无法加载混合模式程序集

时间:2015-04-04 11:17:25

标签: .net

我的所有项目都设置为使用.net 4.5.1 测试项目使用一些针对.NET v2.0.50727的SQl Server程序集。

App.config中:

<startup useLegacyV2RuntimeActivationPolicy="true">
        <supportedRuntime  version="v2.0.50727"/>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1"/>   
</startup>

我还检查过这个帖子: Mixed mode assembly

1 个答案:

答案 0 :(得分:0)

由于启动元素没有为我做,我采用了以下方法:

Detailed explanation

使用以下助手类:

using System;
    using System.Runtime.CompilerServices;
    using System.Runtime.InteropServices;

    public static class RuntimePolicyHelper
    {
        public static bool LegacyV2RuntimeEnabledSuccessfully { get; private set; }

        static RuntimePolicyHelper()
        {
            ICLRRuntimeInfo clrRuntimeInfo =
                (ICLRRuntimeInfo)RuntimeEnvironment.GetRuntimeInterfaceAsObject(
                    Guid.Empty,
                    typeof(ICLRRuntimeInfo).GUID);
            try
            {
                clrRuntimeInfo.BindAsLegacyV2Runtime();
                LegacyV2RuntimeEnabledSuccessfully = true;
            }
            catch (COMException)
            {
                // This occurs with an HRESULT meaning 
                // "A different runtime was already bound to the legacy CLR version 2 activation policy."
                LegacyV2RuntimeEnabledSuccessfully = false;
            }
        }

        [ComImport]
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        [Guid("BD39D1D2-BA2F-486A-89B0-B4B0CB466891")]
        private interface ICLRRuntimeInfo
        {
            void xGetVersionString();
            void xGetRuntimeDirectory();
            void xIsLoaded();
            void xIsLoadable();
            void xLoadErrorString();
            void xLoadLibrary();
            void xGetProcAddress();
            void xGetInterface();
            void xSetDefaultStartupFlags();
            void xGetDefaultStartupFlags();

            [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
            void BindAsLegacyV2Runtime();
        }
    }

在你打电话给SMO之前,先检查一切是否正常

if (!RuntimePolicyHelper.LegacyV2RuntimeEnabledSuccessfully)
                throw new Exception("Could not load SMO");