在 .Net 项目中使用 Git Submodule

在 .NET Core 项目中使用 Git Submodule 的场景通常是:你有一些公共的库、工具类、UI 组件或 SDK,希望在多个项目中复用,同时又希望保持它们作为独立仓库进行开发和维护。这时候用 submodule 就很合适。下面是完整的使用步骤和注意事项。


一、添加 Submodule

1. 在主项目仓库中执行:

 git submodule add https://github.com/your-org/your-library.git src/YourLibrary

2. 初始化并更新 submodule:

git submodule update --init --recursive

3. 提交变更:

git add .gitmodules src/YourLibrary git commit -m "Add submodule YourLibrary"

二、在 .NET Core 项目中引用

有两种常见方式:

方式 1:直接作为项目引用

1. 在主解决方案中添加子项目:

dotnet sln add src/YourLibrary/YourLibrary.csproj

2. 在主项目中引用:

dotnet add src/MainProject/MainProject.csproj reference src/YourLibrary/YourLibrary.csproj

这样子模块的代码会直接参与编译和调试。


方式 2:作为 NuGet 包

如果子模块仓库本身会打包成 NuGet 包,可以:

1. 在子模块目录里生成包:

cd src/YourLibrary dotnet pack -c Release

2. 在主项目中添加本地源或上传到私有 NuGet Server,然后引用。

这种方式更适合多人协作或多个项目依赖同一个库的场景。


三、更新 Submodule

当子模块仓库有更新时:

cd src/YourLibrary
git checkout main
git pull origin main
cd ../..
git add src/YourLibrary
git commit -m "Update YourLibrary submodule"

主项目会记录子模块的 commit id。团队成员只需执行:

git submodule update --init --recursive

就能保持一致。


四、注意事项

1. 避免循环依赖:子模块不能再依赖主项目。

2. 团队协作:确保大家 clone 时用 --recursive

git clone --recursive https://github.com/your-org/your-project.git

3. 切换分支:记得子模块也可能需要单独切换分支。

4. CI/CD:在 CI 脚本中要执行 git submodule update --init --recursive