Software Engineer Encyclopedia
0%
Domain 08 · DevOps, Cloud & Production Engineering · Pillar

Aspire (اللي كان اسمه .NET Aspire): تشغيل نظام كامل محليًا وفي السحابة

Aspire for Distributed .NET Applications

Aspire بيوصف النظام كله في كود (AppHost): الـ API والـ workers والـ Angular app والـ Postgres والـ Redis والـ queue والـ LLM endpoints، وبيشغلهم مع بعض بـ service discovery وconnection strings وOpenTelemetry dashboard، وبيولّد deployment artifacts. بنطبقه على الـ Capstone ونقارن بـ Docker Compose، ونعرف حدوده.

  • Advanced
  • ~8 min read
  • 13 sections
  • 4 code examples
  • 1 diagrams
  • 4 questions
  • Priority L2 · Essential
  • Aspire 13.x (renamed from .NET Aspire at v13, Nov 2025; 13.5 current as of Aug 2026) · .NET 10 · aspire CLI — reviewed 2026-11-18 against aspire.dev

بعد الدرس ده هتقدر

  • تشرح المشكلة اللي Aspire بيحلها (inner loop لنظام موزع) ومكوناته: AppHost، integrations، ServiceDefaults، dashboard
  • تكتب AppHost بيعرّف API وworker وفرونت Angular وPostgres+pgvector وRedis وparameters
  • تفهم service discovery وحقن connection strings وhealth checks وOTel defaults
  • تستخدم الـ dashboard للـ traces والـ logs والـ metrics أثناء التطوير
  • تعرف طرق الـ deployment (aspire publish/deploy، Azure Container Apps، Kubernetes manifests، Compose)
  • تقارن Aspire بـ Docker Compose وتعرف إمتى ما تستخدموش

المتطلبات قبل ما تبدأ

01

المشكلة: «شغّل المشروع» بقت 7 خطوات

The inner-loop problem
Basics

الـ Capstone فيه API و ingestion worker و Angular app و Postgres بـ pgvector و Redis و mock LLM. عشان مطور جديد يشغله: يثبت Postgres، يعمل extension، يشغل Redis، يظبط 6 connection strings، يشغل 4 processes بالترتيب، ويدور على الـ logs في 4 terminals. Aspire بيحوّل ده لملف C#‎ واحد (AppHost) وأمر واحد، وبيضيف dashboard فيه traces و logs و metrics لكل الخدمات من أول يوم.

AppHost (C#)aspire runapi (.NET)worker (.NET)web (Angular/npm)postgresredisDashboard: resources · console logs · structured logs · traces · metrics (OTLP)service discovery + connection strings injected as environment variables
The AppHost models resources and references; Aspire starts them, injects configuration and collects telemetry

تغيير الاسم: من نسخة 13 (نوفمبر 2025) المشروع بقى اسمه Aspire بس (من غير ‎.NET) لأنه بقى بيدعم Python و JavaScript كـ first-class، وفيه aspire CLI (aspire new، aspire run، aspire update، aspire publish/deploy) و AppHost ممكن بـ TypeScript كمان. المفاهيم ثابتة، لكن أسماء الـ APIs اتغيرت بين النسخ (مثلًا AddPythonScript ← AddPythonApp في 13.1) — راجع aspire.dev لنسختك.

02

AppHost للـ Capstone

Modelling the Capstone
Practical
Bashgetting started (CLI)
aspire new                       # pick a template, or add an AppHost to an existing solution:
aspire init
aspire run                       # starts everything + opens the dashboard
C#Knowledge.AppHost/AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);

var pgPassword = builder.AddParameter("pg-password", secret: true);        // from user-secrets / env, never hard-coded
var postgres = builder.AddPostgres("postgres", password: pgPassword)
                      .WithImage("pgvector/pgvector", "pg17")               // image with the pgvector extension
                      .WithDataVolume()                                     // keep data between runs
                      .WithPgAdmin();
var db = postgres.AddDatabase("knowledge");

var redis = builder.AddRedis("redis").WithDataVolume();

var mockLlm = builder.AddProject<Projects.MockLlm>("mock-llm");            // swap for a real endpoint via a parameter

var api = builder.AddProject<Projects.Knowledge_Api>("api")
                 .WithReference(db).WaitFor(db)                             // ConnectionStrings__knowledge injected
                 .WithReference(redis).WaitFor(redis)
                 .WithReference(mockLlm)                                    // service discovery: http://mock-llm
                 .WithExternalHttpEndpoints();

builder.AddProject<Projects.Knowledge_Ingestion>("ingestion")
       .WithReference(db).WaitFor(db)
       .WithReference(redis)
       .WithReference(mockLlm);

builder.AddNpmApp("web", "../web", "start")                               // Angular dev server (JS integration package)
       .WithReference(api)
       .WithHttpEndpoint(env: "PORT")
       .WithExternalHttpEndpoints();

builder.Build().Run();
  • Resources: كل حاجة في النظام (project، container، executable، parameter) resource ليها اسم.
  • WithReference: بيحقن الـ connection string أو عنوان الخدمة في الـ resource التاني كـ environment variables (ConnectionStrings__knowledge، services__mock-llm__http__0).
  • WaitFor: الـ API ما يبدأش قبل ما الـ DB تبقى healthy — بيحل مشكلة «startup لا يعني readiness» من Docker Compose.
  • Parameters: للأسرار والإعدادات اللي بتختلف بين البيئات، بتتقري من user-secrets أو env.
03

ServiceDefaults: الـ cross-cutting مرة واحدة

Shared service defaults
Practical
C#in each .NET service
var builder = WebApplication.CreateBuilder(args);
builder.AddServiceDefaults();        // OpenTelemetry (traces/metrics/logs to OTLP), health checks, service discovery, HttpClient resilience
builder.AddNpgsqlDbContext<AppDb>("knowledge", configureDbContextOptions: o => o.UseNpgsql(x => x.UseVector()));
builder.AddRedisDistributedCache("redis");
builder.Services.AddHttpClient<MockLlmClient>(c => c.BaseAddress = new("https+http://mock-llm"));   // resolved by service discovery

var app = builder.Build();
app.MapDefaultEndpoints();           // /health and /alive in development

مشروع ServiceDefaults هو كود بتاعك (مش black box): بيضيف OTel instrumentation لـ ASP.NET Core و HttpClient و runtime، الـ health checks، والـ standard resilience handler لكل HttpClient. عدّله حسب احتياجك. والـ integrations (Aspire.Npgsql.EntityFrameworkCore.PostgreSQL، Aspire.StackExchange.Redis…) بتضيف الـ client + health check + telemetry لكل dependency بسطر.

04

الـ dashboard: observability من أول يوم

Using the dashboard
Practical

الـ dashboard بيستقبل OTLP من كل الخدمات. طلب chat واحد من Angular هتشوفه trace واحد: الـ API ← Redis (budget) ← Postgres (vector search) ← mock-llm ← الرد — بالـ durations لكل span. ده نفس الـ trace اللي هتشوفه في الإنتاج في Application Insights أو Grafana، فالـ instrumentation اللي كتبته وانت بتطور هو اللي هيشتغل في الإنتاج.

Tabتستخدمه في
Resourcesحالة كل خدمة/container، الـ endpoints، الـ env vars المحقونة (debug للـ config)
Console logsstdout لكل resource في مكان واحد
Structured logsفلترة بالـ trace id أو الـ level أو أي property
Traces«ليه الطلب ده بطيء؟» — span بطيء أو N+1 queries ظاهرة
Metricsrequest rate، durations، runtime (GC، thread pool)

الـ dashboard كمان ممكن يشتغل standalone (container) مع أي تطبيق بيبعت OTLP، حتى من غير AppHost.

05

Integration tests بالـ AppHost

Testing the distributed app
Practical
C#Aspire.Hosting.Testing: spin up the real topology in a test
public sealed class ChatFlowTests
{
    [Fact]
    public async Task Ask_returns_cited_answer_end_to_end()
    {
        var appHost = await DistributedApplicationTestingBuilder.CreateAsync<Projects.Knowledge_AppHost>();
        await using var app = await appHost.BuildAsync();
        await app.StartAsync();

        var http = app.CreateHttpClient("api");                                 // real API, real Postgres container, mock LLM
        await app.ResourceNotifications.WaitForResourceHealthyAsync("api");
        var res = await http.PostAsJsonAsync("/api/questions", new { question = "What is the refund window?" });
        res.EnsureSuccessStatusCode();
        var body = await res.Content.ReadFromJsonAsync<AnswerDto>();
        Assert.NotEmpty(body!.Citations);
    }
}

تقيلة نسبيًا (containers حقيقية)، فخليها لعدد قليل من الـ flows الحرجة — نفس منطق الـ test pyramid. الاختبارات الأسرع لكل خدمة لوحدها بـ WebApplicationFactory و Testcontainers.

06

من التطوير للـ deployment

Publishing and deploying
Deep dive

نفس الـ AppHost بيوصف topology النظام، فـ Aspire يقدر يولّد منه artifacts للـ deployment: aspire publish بيطلّع manifests/IaC حسب الـ target (Docker Compose، Kubernetes، أو Azure: Bicep لـ Azure Container Apps)، و aspire deploy بيعمل deployment مباشر للـ targets المدعومة. القرارات المهمة:

  • Azure Container Apps الأقرب لنموذج Aspire (كل project = container app، Postgres/Redis ← خدمات Azure مُدارة عبر integrations بتعمل provisioning).
  • Kubernetes ممكن عبر الـ publisher أو أدوات زي Aspir8 — بس غالبًا فريق الـ platform عنده Helm/GitOps، فـ Aspire بيبقى للـ inner loop بس.
  • Containers في الـ dev ≠ الإنتاج: Postgres container محليًا يقابله Azure Database for PostgreSQL في الإنتاج — نفس الـ connection string name، provider مختلف. اعرف ده عشان ما تتفاجئش بفروق الإصدارات والـ extensions (pgvector لازم يتفعل على الخدمة المدارة).
  • الأسرار: الـ parameters بتتحول لـ secrets في الـ target (Key Vault/Container Apps secrets)، مش env vars plain.
07

Aspire مقابل Docker Compose

Aspire or Compose?
Deep dive
Docker ComposeAspire
لغة الوصفYAMLC#‎ (أو TypeScript) — refactoring، types، شروط
تشغيل مشاريع ‎.NETلازم تبني imagesبيشغلها كـ processes مباشرة (debugger، hot reload)
Config wiringيدوي (env vars)WithReference بيحقنها
Observabilityتجيب stack بنفسكdashboard مدمج + ServiceDefaults
غير ‎.NETأي حاجةcontainers + Python/JS integrations (أوسع من الأول بكتير من 13)
الفريقمعروف للكلمحتاج تعلم، وبيتطور بسرعة (breaking changes بين majors)

التوصية: لنظام معظمه ‎.NET وفريق ‎.NET، Aspire بيوفر وقت كبير في الـ inner loop والـ onboarding. لو النظام متعدد اللغات بشكل كبير أو فريق الـ ops مستقر على Compose/K8s، Compose لسه اختيار ممتاز. الـ Capstone فيه الاتنين: docker-compose.yml كـ baseline محايد، و AppHost كخيار للتطوير.

08

إزاي الـ configuration بتوصل للخدمة؟ trace كامل

How configuration flows
Deep dive

لما تكتب .WithReference(db)، Aspire بيعمل التالي وقت aspire run: (1) يشغّل الـ Postgres container ويستنى الـ health check، (2) يبني connection string من الـ host/port/password الفعليين، (3) يحقنها في process الـ API كـ environment variable ConnectionStrings__knowledge، (4) الـ API بيقراها بالـ configuration system العادي في ‎.NET (builder.Configuration.GetConnectionString("knowledge")) — مفيش سحر في الكود، هي نفس الـ configuration providers من Developer Workflow.

في الـ AppHostبيوصل للخدمة كـبتقراه بـ
WithReference(db)ConnectionStrings__knowledgeGetConnectionString("knowledge") أو الـ integration (AddNpgsqlDbContext("knowledge"))
WithReference(api) (خدمة HTTP)services__api__https__0service discovery: https+http://api في HttpClient
WithEnvironment("Llm__Model", "small")Llm__ModelIOptions<LlmOptions>
AddParameter("key", secret: true)قيمة من user-secrets/envنفس الـ configuration

الفايدة إن نفس الكود بيشتغل من غير Aspire خالص (في Kubernetes مثلًا) طالما الـ environment variables بنفس الأسماء موجودة — Aspire مش dependency لازم في الإنتاج. وده سؤال مهم في الـ adoption: «لو قررنا نشيل Aspire بعد سنة، هنغير إيه؟» الإجابة: الـ AppHost بس، مش الخدمات.

09

Aspire والـ AI workloads

AI resources in the AppHost
Practical
  • Model endpoints كـ resources: integrations لـ Azure OpenAI/AI Foundry بتعمل provisioning في Azure وبتحقن الـ endpoint، أو connection string لـ OpenAI-compatible endpoint (Ollama/vLLM محلي) — والكود بيستخدم IChatClient في الحالتين.
  • Python services: worker الـ embeddings أو الـ evals بـ Python يتضاف للـ AppHost (Python integration)، ويطلع في نفس الـ dashboard والـ traces مع خدمات ‎.NET.
  • Telemetry للـ LLM calls: الـ OTel GenAI attributes (model، tokens) بتظهر في الـ traces في الـ dashboard وانت بتطور، فتشوف تكلفة كل request قبل الإنتاج.
  • Eval runs: AppHost profile منفصل بيشغّل الـ stack + الـ eval harness على الـ golden set — نفس الـ topology اللي في CI.
10

أخطاء شائعة

Common mistakes
Basics
  • اعتبار Aspire «platform إنتاج» بيلغي الحاجة لفهم Docker/K8s/Azure — هو أداة وصف وتشغيل؛ الإنتاج لسه محتاج قرارات تشغيل.
  • Hard-coded passwords في الـ AppHost بدل parameters سرية.
  • Upgrade لنسخة major جديدة من غير aspire update وقراءة الـ breaking changes.
  • الاعتماد على containers dev بإصدارات مختلفة عن الخدمات المُدارة في الإنتاج من غير اختبار.
  • Integration tests بالـ AppHost لكل حاجة ← suite بطيئة جدًا.
11

اختبر فهمك

Knowledge check
Basics

الـ API بيفشل عند البداية لأن Postgres لسه بيعمل initialize. الحل في Aspire؟

إيه اللي بيعمله WithReference(db)؟

12

تمرين محلول

Worked exercise
Practical
ضيف Ollama محلي كبديل للـ mock LLM بـ parameter يختار بينهم

الحل: في الـ AppHost: var useOllama = builder.Configuration["UseOllama"] == "true"; ثم IResourceBuilder<IResourceWithServiceDiscovery> llm = useOllama ? builder.AddContainer("ollama", "ollama/ollama").WithHttpEndpoint(targetPort: 11434, name: "http").WithVolume("ollama-models", "/root/.ollama") … : builder.AddProject<Projects.MockLlm>("mock-llm"); (أو استخدم integration مجتمعية لـ Ollama لو متاحة لنسختك)، والـ API بياخد WithReference(llm). الكود في الـ API ما بيتغيرش لأنه بيكلم IChatClient بعنوان من الـ service discovery. وشغّل الـ eval suite على الاتنين وقارن الجودة والـ latency — ده بالظبط قسم «موديل حقيقي» في Capstone Build-Along.

13

أسئلة إنترفيو

Interview questions
Basics
(Mid) Aspire بيحل إيه؟
الـ inner loop لتطبيق موزع: وصف كل الخدمات والـ dependencies في AppHost واحد، تشغيلهم بأمر واحد مع wiring تلقائي للـ config والـ service discovery، و observability مدمجة، وتوليد deployment artifacts من نفس الوصف.
(Senior) تعتمد Aspire لفريق 20 مهندس؟
بقيّم: هل النظام معظمه ‎.NET؟ وقت الـ onboarding والـ «works on my machine» الحالي؟ استعداد الفريق لمواكبة إصدارات سريعة؟ أبدأ بيه للـ inner loop والـ integration tests، وأخلي الإنتاج على IaC/GitOps الموجود لحد ما الـ publishers تثبت كفاءتها عندنا.
↗

المراجع والقراءة الإضافية

References & further reading

الدرس بيشرح الفكرة نفسها؛ الروابط دي للتحقق والتعمق والرجوع لتفاصيل الـ API. (محتاجة إنترنت.)

التوثيق الرسمي — Official documentation

خلصت الدرس وحليت الأسئلة؟ علّم عليه عشان يتحسب في تقدّمك.

محتويات الدرس