コンテンツにスキップ
Docs Try Aspire
Docs Try

Rust integration

このコンテンツはまだ日本語訳がありません。

Rust logo

The Aspire Rust hosting integration enables you to run Rust applications alongside other resources in your AppHost project, providing service discovery, health checks, and observability for your Rust services.

⭐ Community Toolkit
Aspire CLI — CommunityToolkit.Aspire.Hosting.Rust パッケージを追加
aspire add communitytoolkit-rust

Aspire CLI は対話的です。求められたら適切な結果を選択してください:

Aspire CLI — 出力例
Select an integration to add:
> communitytoolkit-rust (CommunityToolkit.Aspire.Hosting.Rust)
> Other results listed as selectable options...

In your AppHost, call AddRustApp to register a Rust application as a resource. Provide the resource name and the path to the directory containing your Rust project (where Cargo.toml lives):

AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var rustApp = builder.AddRustApp("rust-api", workingDirectory: "../rust-app")
.WithHttpEndpoint(port: 8080, env: "PORT");
builder.AddProject<Projects.ExampleProject>("apiservice")
.WithReference(rustApp);
builder.Build().Run();

The Aspire app host runs cargo run in the specified workingDirectory to start your Rust application. The required parameters are:

  • name — the resource name shown in the Aspire dashboard.
  • workingDirectory — path to the directory containing the Rust application.

Rust applications typically read a PORT environment variable to determine which port to listen on. Use WithHttpEndpoint to expose an HTTP endpoint and inject the port value as an environment variable:

AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var rustApp = builder.AddRustApp("rust-api", "../rust-app")
.WithHttpEndpoint(port: 8080, env: "PORT");
builder.Build().Run();

Your Rust application can read the injected environment variable as follows:

main.rs
use std::env;
use actix_web::{web, App, HttpServer, Responder};
async fn greet() -> impl Responder {
"Hello from Rust!"
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let port = env::var("PORT").unwrap_or_else(|_| "8080".to_string());
let addr = format!("0.0.0.0:{}", port);
println!("Server listening on {}", addr);
HttpServer::new(|| {
App::new()
.route("/", web::get().to(greet))
})
.bind(addr)?
.run()
.await
}

To pass custom arguments to cargo run, chain the WithArgs method:

AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var rustApp = builder.AddRustApp("rust-api", "../rust-app")
.WithArgs("--release")
.WithHttpEndpoint(port: 8080, env: "PORT");
builder.Build().Run();