如何将.NET Framework DLL作为.NET 6.0 DLL的依赖项使用?
问题描述
- 正在将.NET Framework应用移植到.NET 6.0,主应用基于
net6.0-windowsSDK构建,仅运行于Windows平台 - 依赖一组第三方.NET Framework 4.5.2 DLL,短期内无法移植到.NET或.NET Standard
- 主应用直接调用这些第三方DLL时运行正常;但通过同样基于
net6.0-windows构建的.NET 6.0中间DLL调用第三方DLL(主应用不直接引用第三方DLL)时,会触发MissingMethodException异常
解决方案
1. 配置中间DLL项目
在中间DLL的.csproj文件中添加兼容配置,确保能正确加载.NET Framework程序集:
<PropertyGroup> <TargetFramework>net6.0-windows</TargetFramework> <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType> <!-- 若涉及WinForms/WPF,添加对应启用配置 --> <EnableWindowsForms>true</EnableWindowsForms> <UseWindowsForms>true</UseWindowsForms> </PropertyGroup> <ItemGroup> <Reference Include="你的第三方DLL名称"> <HintPath>第三方DLL的路径</HintPath> <Private>true</Private> <SpecificVersion>false</SpecificVersion> </Reference> </ItemGroup>
2. 主应用添加绑定重定向
在主应用的app.config中添加绑定重定向,确保第三方DLL的版本能被正确解析:
<configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="第三方DLL名称" publicKeyToken="对应公钥令牌" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-4.5.2.0" newVersion="4.5.2.0" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration>
3. 确保第三方DLL存在于主应用输出目录
- 中间DLL项目中引用第三方DLL时,
Private设置为true会自动将DLL复制到主应用输出目录 - 若未自动复制,可手动将第三方DLL复制到主应用的
bin/Debug/net6.0-windows或bin/Release/net6.0-windows目录
4. 启用平台兼容开关
在主应用的Program.cs入口处添加以下代码,强制启用Windows平台的.NET Framework兼容加载:
using System.Runtime.Versioning; [assembly: SupportedOSPlatform("windows")] // 若第三方DLL涉及二进制序列化,添加此开关 AppContext.SetSwitch("Switch.System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization", true);
内容的提问来源于stack exchange,提问作者Betabot
相关产品推荐
相关产品推荐

