在 dotnet 运行 的解决方案中设置默认项目

Set default project in solution for dotnet run

我在它自己的文件夹中创建了一个解决方案和一个 webapi 项目。 然后我将项目添加到解决方案中。

我希望能够 运行 dotnet run 而无需通过设置默认值指定项目(就像我在 Visual Studio 中那样)

使用 CLI 是否可行?

目前,dotnet run无法做到这一点。

dotnet run 确实调用 msbuild 目标来进行恢复和构建,但会从新的静态评估中查询实际程序和 运行 的参数,这意味着即使您将自定义构建逻辑添加到一个解决方案(=> "project" 正在构建),你没有机会 运行 自定义 msbuild 逻辑来从其他项目中获取这些属性。 (仍然可以对构建的可执行文件的相对路径进行硬编码,但这非常麻烦且不太灵活)

这意味着最好的方法是创建 scipts(.bat、.sh)来为您调用正确的 dotnet run -p my/project 命令,而无需您进行大量输入。

似乎还没有 dotnet 配置文件 - 很高兴看到 .dotnetconfig.json 或类似文件,否则扩展 SLN 文件以支持 dotnet 命令的默认项目。按照@MartinUllrich 的思路,假设您安装了 Node.js,只需创建一个 package.json 并调用 npm start。同样的模式也适用于其他脚本引擎。

package.json

{
  "name": "dotnet-run-default-project",
  "private": true,
  "version": "1.0.0", 
  "scripts": {
    "start": "dotnet run -p .\src\MyApplication.Web\"
  }
}

运行 默认项目

npm start

如果您使用的是 *nix 系统,Makefile 可以解决所有重复输入问题。

我通常创建一个高级别Makefile来缩短常用命令。

build:
    dotnet build
clean:
    dotnet clean
restore:
    dotnet restore
watch:
    dotnet watch --project src/Main/Main.csproj run
start:
    dotnet run --project src/Main/Main.csproj

以上命令与干净的体系结构设置相关,其中文件结构大致类似于以下树。

-- root
|-- src
|    |-- Application
|    |-- Core
|    |-- Infrastructure
|    |-- Main
|-- tests
|    |-- Application.IntegrationTests
|    |-- Core.UnitTests
|    |-- Infrastructure.UnitTests
|-- API.sln
|-- Makefile

通过该设置,我可以运行命令

make start

另一种方法是将项目文件移动到解决方案目录。然后当执行 dotnet run 时,它会检查该目录以加载项目。

之后您不需要指定 --project :)