Skillpedia
واجهات API والخوادم (backend)40k · #7302

mvvm-toolkit-di

ما الذي تفعله

تساعد هذه «المهارة» على ربط أجزاء الكود المسماة «ViewModels» بأجزاء أخرى توفر الخدمات (مثل حفظ الملفات أو إرسال الرسائل) بطريقة منظمة. وتستخدم نظاماً يُسمى «حقن الاعتماديات» (Dependency Injection) ليجد الأجزاء المناسبة بعضها تلقائياً.

متى تستخدمها

  • ✓عندما تُعدّ تطبيقاً جديداً بواجهة رسومية (WPF أو MAUI وغيرهما) وتحتاج إلى تنظيم تواصل أجزاء البرنامج.
  • ✓لتحديد مدة بقاء الخدمة أو الـ ViewModel (إلى الأبد، أو فقط عند الحاجة، وغير ذلك).
  • ✓لضمان إعداد التواصل بالرسائل بين أجزاء التطبيق بشكل صحيح وفي الأماكن المطلوبة.

رابط المهارة

https://github.com/github/awesome-copilot/blob/main/skills/mvvm-toolkit-di/SKILL.md

انسخه والصقه في الذكاء الاصطناعي الذي تستخدمه (Claude أو ChatGPT أو Cursor) واطلب منه اتباع التعليمات.

طريقة الاستخدام

أسهل طريقة: انسخ الرسالة والصقها في الذكاء الاصطناعي الذي تستخدمه. سيقرأ المهارة وينفّذ تعليماتها.

رسالة جاهزة للصق

استخدم هذه المهارة لمساعدتي: https://github.com/github/awesome-copilot/blob/main/skills/mvvm-toolkit-di/SKILL.md اقرأ ملف SKILL.md في هذا الرابط ونفّذ تعليماته لمهمتي.
تريد أن يجد الذكاء الاصطناعي مهارات مثل هذه بنفسه؟ثبّت خادم Skillpedia MCP المجاني: سطر واحد، ويبحث في 15,000+ مهارة قبل كل مهمة.ثبّته في دقيقة واحدة →

مثال على ما تطلبه من الذكاء الاصطناعي

“كيف أُعدّ تطبيقي ليعرف كيف ينشئ الـ ViewModels والخدمات الخاصة بي ويوفّرها؟”

5 مهارات جديدة كل أسبوع. قراءة في دقيقة واحدة.

كيف تعمل

تستخدم نظام «حقن الاعتماديات»، الذي يعمل كمنظّم. تخبره بالخدمات الموجودة وطريقة إنشائها، فيتولى توصيلها تلقائياً إلى الأماكن التي تحتاجها، غالباً عبر مُنشئات الصفوف (constructors).

المحتوى التقني (ملف SKILL.md الأصلي)

النص الأصلي من المؤلف، مباشرة من GitHub.

CommunityToolkit.Mvvm + Microsoft.Extensions.DependencyInjection

The MVVM Toolkit deliberately ships no DI container — it composes with Microsoft.Extensions.DependencyInjection, the same container ASP.NET Core, Worker services, and the .NET Generic Host use.

TL;DR. Build the service provider once at startup (prefer Host.CreateDefaultBuilder()). Register services and ViewModels. Inject through constructors. Avoid Ioc.Default.GetService<T>() in user code.


When to use this skill

  • Standing up the composition root for a new XAML app (WPF, WinUI 3, MAUI, Uno, Avalonia)
  • Choosing service/VM lifetimes
  • Wiring IMessenger once and injecting it into ObservableRecipient ViewModels
  • Resolving a page's ViewModel without coupling to a service locator
  • Diagnosing "Unable to resolve service for type X while attempting to activate Y"

For source generators and ViewModel patterns see the mvvm-toolkit skill. For Messenger pub/sub see mvvm-toolkit-messenger.


Recommended composition root (Generic Host)

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using CommunityToolkit.Mvvm.Messaging;

public partial class App : Application
{
    public IHost Host { get; }

    public App()
    {
        Host = Microsoft.Extensions.Hosting.Host
            .CreateDefaultBuilder()
            .ConfigureServices((_, services) =>
            {
                services.AddSingleton<IFilesService, FilesService>();
                services.AddSingleton<ISettingsService, SettingsService>();
                services.AddSingleton<IMessenger>(WeakReferenceMessenger.Default);

                services.AddSingleton<ShellViewModel>();
                services.AddTransient<ContactViewModel>();
                services.AddTransient<EditorViewModel>();
            })
            .Build();
    }

    public static T GetService<T>() where T : class =>
        ((App)Current).Host.Services.GetRequiredService<T>();
}

Generic Host benefits:

  • appsettings.json binding via Microsoft.Extensions.Configuration
  • Logging via Microsoft.Extensions.Logging
  • Hosted services (IHostedService) for background work
  • Scope validation in development builds

WPF and Windows Forms must integrate the host lifetime with the app lifetime — see Use the .NET Generic Host in a WPF app.

Without Generic Host

When you only need a service container and want zero extra dependencies:

var services = new ServiceCollection();
services.AddSingleton<IFilesService, FilesService>();
services.AddTransient<ContactViewModel>();
ServiceProvider provider = services.BuildServiceProvider();

Constructor injection

Inject services and child ViewModels through the constructor:

public sealed partial class ContactViewModel(
    IFilesService files,
    IMessenger messenger,
    ILogger<ContactViewModel> logger)
    : ObservableRecipient(messenger)
{
    [ObservableProperty]
    private string? name;

    [RelayCommand]
    private async Task SaveAsync()
    {
        logger.LogInformation("Saving {Name}", Name);
        await files.SaveAsync(Name!);
    }
}

Why constructor injection beats a service locator:

  • Dependencies are explicit and visible at the call site
  • Unit tests inject fakes/mocks directly
  • The DI container validates the dependency graph at startup
  • Missing registrations throw immediately, not at first use

Lifetimes

Lifetime Method Typical use in XAML apps
Singleton AddSingleton<T> Shell/main-window VM, settings, file/HTTP services, the shared IMessenger, app-wide caches
Transient AddTransient<T> Per-page or per-document ViewModels (a fresh instance every resolve)
Scoped AddScoped<T> Rarely needed in client apps; useful with explicit IServiceScope (e.g., per-window scopes)
services.AddSingleton<ShellViewModel>();   // 1 instance for app lifetime
services.AddTransient<NoteViewModel>();    // new instance per resolve
services.AddScoped<DialogService>();       // 1 per scope (rare)

Resolving in a View

Resolve the page's root ViewModel in code-behind, then let it pull its own dependencies:

public sealed partial class ContactPage : Page
{
    public ContactViewModel ViewModel { get; }


…
الأسئلة الشائعة

ما هو «حقن الاعتماديات» (Dependency Injection)؟

هو أسلوب لتنظيم الكود، فبدلاً من أن ينشئ الصف اعتماداته (الصفوف الأخرى التي يحتاجها)، تُمرَّر هذه الاعتماديات إليه من الخارج. وهذا يجعل الكود أكثر مرونة وأسهل في الاختبار.

ما الفرق بين Singleton وTransient وScoped؟

Singleton: نسخة واحدة فقط تبقى طوال عمر التطبيق. Transient: تُنشأ نسخة جديدة في كل مرة تُطلب فيها. Scoped: تُنشأ نسخة لكل «نطاق» محدد، مثل نافذة أو طلب (وهي أقل شيوعاً في تطبيقات سطح المكتب).

لماذا لا يجب أن أنشئ الـ ViewModels يدوياً؟

الإنشاء اليدوي قد يؤدي إلى كود يصعب إدارته واختباره. أما استخدام «حقن الاعتماديات» فيضمن حل الاعتماديات بشكل صحيح، ولا تحتاج إلى القلق بشأن طريقة إنشائها في كل مرة.

التفاصيل

الوصف الأصلي من المؤلف

Wire CommunityToolkit.Mvvm ViewModels into Microsoft.Extensions.DependencyInjection. Covers the .NET Generic Host composition root, constructor injection, service lifetimes (Singleton / Transient / Scoped), IMessenger registration, resolving ViewModels in Views, keyed services, testing seams, and the legacy Ioc.Default escape hatch. Use across WPF, WinUI 3, .NET MAUI, Uno, and Avalonia.

repo: github/awesome-copilot

الشعبية

نجوم GitHub
40k
الترتيب
#7302
الترخيص
MIT
آخر تحديث
15‏/10‏/2026

هل هذه المهارة مفيدة؟

0

سجّل الدخول للتصويت.

التعليقات

  • …

المزيد من المهارات من هذا المستودع

مهارات مشابهة