You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core 8.x中正确处理依赖库二级依赖的方法

问题背景

我正在开发一个应用,该应用依赖DataService.dll,而该DLL又依赖SQLite组件。主应用无直接依赖SQLite,但会调用DataService中操作SQLite的功能。主应用csproj通过以下方式引用DataService:

<ItemGroup>
    <Reference Include="DataService">
      <HintPath>.\External\DataService.dll</HintPath>
    </Reference>
</ItemGroup>

遇到的问题

主应用构建后调用DataService方法时出现运行时错误,提示找不到Microsoft.EntityFrameworkCore程序集,SQLite相关依赖未被包含。有以下疑问:

  • 是否需要直接执行dotnet add package SQLite添加直接依赖?这似乎不合理;
  • 为何dotnet build不会自动发现DataService的依赖并包含SQLite?
  • 需做什么配置才能引入二级依赖?

错误信息

Unhandled exception. System.IO.FileNotFoundException: Could not load
file or assembly 'Microsoft.EntityFrameworkCore, Version=9.0.0.0,
Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot
find the file specified.

File name: 'Microsoft.EntityFrameworkCore, Version=9.0.0.0,
Culture=neutral, PublicKeyToken=adb9793829ddae60'

解决方案

为什么dotnet build不会自动包含二级依赖?

直接通过<Reference>标签引用本地DLL时,.NET仅会确认该DLL存在并用于编译,但不会解析该DLL的依赖元数据,也不会自动拉取或复制其依赖文件到主应用的输出目录。这种引用方式本质是“裸引用”,不会处理依赖链。

不需要直接添加SQLite依赖,推荐以下处理方式:

1. 改用项目引用(最推荐)

如果DataService是你维护的项目,将其加入解决方案,主应用通过项目引用关联:

<ItemGroup>
  <ProjectReference Include="..\DataService\DataService.csproj" />
</ItemGroup>

这种方式下,.NET会自动解析整个依赖链,编译时将DataService及其所有依赖(包括EF Core、SQLite)一并复制到主应用输出目录。

2. 手动复制依赖项(仅适用于无法使用项目引用的场景)

若必须使用本地DLL引用,需手动将DataService的依赖文件复制到主应用输出目录:

  • 找到DataService依赖的Microsoft.EntityFrameworkCore.dll、Microsoft.EntityFrameworkCore.Sqlite.dll等文件;
  • 在主应用csproj中添加复制指令:
    <ItemGroup>
      <None Include=".\External\Microsoft.EntityFrameworkCore.dll">
        <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      </None>
      <None Include=".\External\Microsoft.EntityFrameworkCore.Sqlite.dll">
        <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      </None>
    </ItemGroup>
    
    注意:这种方式需手动维护所有依赖,DataService依赖版本更新时需同步更新文件,易出错。

3. 将DataService打包为NuGet包(最佳实践)

把DataService打包成NuGet包,并在包的配置中声明其依赖项(EF Core、SQLite)。主应用通过NuGet安装DataService包时,NuGet会自动下载并安装所有依赖,编译时自动复制到输出目录。

内容的提问来源于stack exchange,提问作者raddevus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 23:03:22