首页 文章

如何在.Net 5中加载为另一个.net版本构建的.dll?

提问于
浏览
7

在以前的ASP.NET版本中(直到版本4.6),我们可以通过修改web.config来加载为另一个.net版本构建的* .dll,如下所示:

<configuration>
     <startup useLegacyV2RuntimeActivationPolicy="true" >   
     </startup>
</configuration>

但是在ASP.NET 5中,没有web.config,而是一个完全不同的配置系统 . 那么我们如何才能在新版本中获得相同的结果呢?

1 回答

  • 2

    这篇博客文章展示了如何在运行时设置此策略(相对于"design-time" - 通过编辑web.config)http://reedcopsey.com/2011/09/15/setting-uselegacyv2runtimeactivationpolicy-at-runtime/但我还没有尝试过使用ASP.NET 5 . 虽然工作在早期版本 .

    基本上你创建这个静态助手类

    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();
        }
    }
    

    用法:

    // before calling the code from your legacy assembly - 
    if (RuntimePolicyHelper.LegacyV2RuntimeEnabledSuccessfully)
    {
        // your Legacy code
    }
    

相关问题