如何使用 Bullseye 定义 .NET 项目的构建目标?

来源:这里教程网 时间:2026-02-21 17:28:08 作者:

在 .NET 项目中使用 Bullseye 并不是直接“定义构建目标”的标准方式,因为 Bullseye 是一个基于 .NET 的外部命令行任务运行器,用于替代或补充传统的构建脚本(如 Make、PSake 或 Invoke-Build)。它本身不参与 MSBuild 构建过程,而是用来组织和执行一系列自定义命令或步骤,比如清理、编译、测试、打包等。

什么是 Bullseye?

Bullseye 是一个轻量级的 .NET 库,允许你用 C# 定义命名任务(tasks),并从命令行运行它们。它常用于简化 CI/CD 脚本或本地开发流程。

要使用 Bullseye 来管理 .NET 项目的“构建目标”,你需要:

安装 Bullseye NuGet 包 定义任务(如 build、test、clean) 通过命令行触发这些任务

1. 添加 Bullseye 到项目

在你的 .NET 项目(通常是工具项目或根目录的脚本项目)中添加 Bullseye 包引用:

dotnet add package Bullseye

建议同时添加 Microsoft.Extensions.CommandLineUtils 来更好地处理参数。

2. 定义构建任务

创建一个入口类(如 Program.cs),定义常用构建目标:

using System; using static Bullseye.Internal.ConsoleColors;

var target = args.Length > 0 ? args[0].ToLowerInvariant() : "default";
var targets = new Dictionary>();

targets["clean"] = async () =>
{
  Console.WriteLine("Cleaning output directories...");
  await Command.RunAsync("dotnet", "clean");
};

targets["build"] = async () =>
{
  Console.WriteLine("Building the solution...");
  await Command.RunAsync("dotnet", "build --no-restore");
};

targets["test"] = async () =>
{
  Console.WriteLine("Running tests...");
  await Command.RunAsync("dotnet", "test");
};

targets["restore"] = async () =>
{
  Console.WriteLine("Restoring packages...");
  await Command.RunAsync("dotnet", "restore");
};

// 构建依赖关系
targets.Add("default", async () =>
{
  await targets["restore"]();
  await targets["clean"]();
  await targets["build"]();
  await targets["test"]();
});

// 运行指定目标
if (targets.TryGetValue(target, out var action))
{
  await action();
}
else
{
  Console.WriteLine($"Unknown target: {target}");
}

3. 使用命令行运行构建目标

编译并运行你的任务程序:

dotnet run -- build

其他可用命令:

dotnet run -- clean dotnet run -- test dotnet run (运行 default)

4. 高级用法:支持异步与错误处理

Bullseye 支持任务依赖、并行执行和颜色输出。更推荐使用其原生 API 注册任务:

Targets.Define("build", async () =>
{
  await Command.RunAsync("dotnet", "build -c Release");
});

Targets.Define("pack", DependsOn("build"), async () =>
{
  await Command.RunAsync("dotnet", "pack -c Release -o ./artifacts");
});

await Targets.RunAsync(args);

这样你可以清晰地表达任务之间的依赖关系。

基本上就这些。Bullseye 不替代 MSBuild,而是帮你把 .NET CLI 命令组织成可复用、可读性强的“构建目标”。适合统一团队开发和 CI 脚本逻辑。

相关推荐