الانتقال إلى المحتوى
.NETASP.NET Core· 9 دقائق للقراءة

فخ الـ Captive Dependency: لما الـ Singleton يمسك في Scoped service

الـ singleton بيفضل ماسك كل dependency اتبنى بيها، فالـ DbContext الـ scoped اللي جواه بيبقى مشترك بين كل الـ requests. إيه اللي بيبوظ، والـ scope check بيمسك إيه، وبيفوّت إيه.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • .NET 10
محتويات المقال

pull request بيغيّر سطر واحد: AddScoped<PriceService>() بقت AddSingleton<PriceService>(). والمنطق شكله سليم: الـ class مفيهاش state خاص بيها، وبتشتغل في كل صفحة منتج، و instance واحدة أرخص من واحدة لكل request. الـ unit tests عدّت، لأنها بتبني PriceService بـ new. والـ production قام من غير ولا كلمة. بعدها بيوم وصل اتنين bug reports: تغييرات الأسعار اللي بتتعمل من الـ admin panel مش بتظهر في صفحات المنتجات، وتحت الضغط فيه requests بتفشل بـ "A second operation was started on this context instance before a previous operation completed". ومحدش لمس كود الداتابيز أصلًا.

الفكرة الغلط الشائعة

الفكرة بتقول إن الـ مجرد مفتاح للـ performance. الـ singleton بيوفّر allocations، والـ transient بيكلّف شوية، والـ scoped في النص، وأي service ينفع تعتمد على أي service تانية لأن الـ container هيربطهم ببعض في كل الأحوال.

وسهل تصدّق ده. الـ docs بتاعة الـ lifetimes بتتكلم فعلًا عن التكلفة: الـ transient بيعمل "per-request allocations". والـ class اللي كل اللي فيها field جاي من الـ injection شكلها فعلًا stateless. وفي الـ production الـ container بيقبل التسجيل ساكت، فمفيش أي حاجة بتقولك إنك كسرت قاعدة.

الافتراض المستخبي هنا إن الـ class تبقى stateless لو الكود بتاعها نفسه مش شايل state. بس الـ dependencies بتاعتها بتتحسب برضه. الـ PriceService ماسكة ShopDb، والـ DbContext مليان state: change tracker، والعملية اللي شغالة دلوقتي، و connection. والـ guidelines بتاعة Microsoft بتقول عكس الفكرة دي: استخدم singleton بس للـ service اللي الـ state بتاعها غالي تعمله أو معمول عشان يتشارك، وابعد عنه للـ services اللي مفيهاش state، لأنها رخيصة جدًا كـ transient.

اللي بيحصل فعلًا

الـ singleton بيتبني مرة واحدة، بكل اللي طلبه

الـ container بيعمل الـ singleton أول مرة حد يطلبه، وبيرجّع نفس الـ instance دي طول عمر التطبيق. الـ constructor بيشتغل مرة واحدة، فكل dependency بتتعمل resolve مرة واحدة وتتخزن في field. ومهما كان الـ lifetime اللي الـ dependency دي متسجلة بيه، هي دلوقتي هتعيش بالظبط قد الـ singleton. ودي اللي اسمها : service عمرها أطول ماسكة service عمرها أقصر ومش سايباها.

المحبوسة جاية من الـ root scope، مش من request

ممكن تتوقع إن الـ singleton هيمسك الـ instance بتاعة أول request. لأ. الـ singleton بيتعمله resolve من الـ root provider، فالـ dependencies الـ scoped بتاعته بتيجي من الـ root scope، وده scope عمر ما أي request بيستخدمه. في تجربة، middleware كان بيحط الـ tenant بتاع كل request في TenantContext متسجل scoped، و singleton عامل inject لنفس الـ TenantContext كان بيشوف null في كل request. والـ docs بتوصف النتيجة: الـ scoped service اللي بتتعمل في الـ root container بتبقى عمليًا singleton، ومش بتتعمل dispose غير لما التطبيق يقفل.

ده بيعمل إيه في الـ DbContext

الـ DbContext معمول لـ unit of work واحدة قصيرة، ومش thread-safe. ولما يبقى مشترك بين كل الـ requests، بيبوظ بتلات طرق:

  • الاستخدام في نفس الوقت بيرمي exception. في تجربة فيها 200 request متوازيين على context واحد محبوس، 169 فشلوا بـ exception الـ "second operation".
  • القراية بتبقى قديمة. الـ FindAsync بيرجّع الـ entity اللي الـ context بيعملها tracking أصلًا من غير ما يسأل الداتابيز. وفي نفس التجربة، سعر request تاني غيّره لـ 12 فضل بيتقري 10.
  • الـ memory بتزيد وبس. كل entity بيتعملها tracking بتفضل في الـ change tracker لحد ما التطبيق يقف.

الـ bug اللي في سطر واحد، بعد الـ fix

النسختين بيستخدموا نفس الـ context، ShopDb، وفيه Products:

C# Program.cs
var builder = WebApplication.CreateBuilder(args);builder.Services.AddDbContext<ShopDb>();// "It keeps no state, so a singleton is cheaper"builder.Services.AddSingleton<PriceService>();var app = builder.Build();app.MapGet("/products/{id:int}/price",    async (int id, PriceService prices) => await prices.GetAsync(id));app.Run();public sealed class PriceService(ShopDb db){    // One ShopDb from the root scope, shared by every request    public async Task<decimal?> GetAsync(int id) =>        (await db.Products.FindAsync(id))?.Price;}

الـ hosted services هي المكان اللي مينفعش فيه تغيّر الـ lifetime وخلاص، لأن AddHostedService بيسجّلها singleton. ماتعملش inject للـ context هناك. اعمل inject لـ IServiceScopeFactory واعمل scope لكل unit of work:

C# SaleExpiry.cs
using Microsoft.EntityFrameworkCore;public sealed class SaleExpiry(IServiceScopeFactory scopes) : BackgroundService{    protected override async Task ExecuteAsync(CancellationToken ct)    {        using var timer = new PeriodicTimer(TimeSpan.FromMinutes(5));        while (await timer.WaitForNextTickAsync(ct))        {            // One scope per run: a fresh ShopDb, disposed when the run ends            await using var scope = scopes.CreateAsyncScope();            var db = scope.ServiceProvider.GetRequiredService<ShopDb>();            await db.Products.Where(p => p.SaleEndsAt < DateTime.UtcNow)                .ExecuteUpdateAsync(s => s.SetProperty(p => p.OnSale, false), ct);        }    }}

الـ scope check بيمسك إيه

في الـ Development environment، الـ WebApplication.CreateBuilder بيشغّل اتنين checks: الـ ValidateScopes بيرفض أي scoped service بتتعمل resolve من الـ root أو بيستخدمها singleton، والـ ValidateOnBuild بيبني كل التسجيلات وقت الـ startup. وفي تجربة على .NET 10، الاتنين مع بعض بيمسكوا أشكال وبيفوّتوا أشكال:

الـ singleton بيوصل للـ scoped service إزايDevelopmentProduction
parameter في الـ constructorالـ startup بيفشل: "Cannot consume scoped service 'ShopDb' from singleton 'PriceService'"بيقوم، و instance واحدة مشتركة
عن طريق transient في النصالـ startup بيفشل، وبيذكر اسم الـ transientبيقوم، و instance واحدة مشتركة
factory lambda أو IServiceProvider متعمله injectبيقوم، وأول استخدام بيرمي "Cannot resolve scoped service ... from root provider"بيقوم، و instance واحدة مشتركة
transient فيه state بيتغيرمش بيتكشفمش بيتكشف

آخر صف بيفكّرك إن الـ validation مش فاهم غير الـ scopes. والـ guidelines بتقول إن الـ transient اللي بيستخدمه singleton ممكن يحتاج يبقى thread-safe، حسب الـ singleton بيستخدمه إزاي. وفي التجربة، counter متسجل transient ومحبوس في singleton فضل يعدّ من request للتاني في الاتنين environments.

تطبقها إزاي في مشروعك

  1. شغّل الاتنين checks برّه الـ Developmentفعّل ValidateScopes و ValidateOnBuild في الـ staging وفي الـ integration tests، أو في كل الـ environments. ساعتها أي captive في constructor هيفشل قبل ما أي traffic يوصل.
  2. خلّي الـ scoped هو الأساس جنب الـ requests والداتابيزالـ services اللي بتستخدم DbContext، والـ repositories، وأي حاجة شايلة داتا خاصة بـ user، كلها scoped. وخلّي الـ service تبقى singleton بس لو هي thread-safe وشايلة state معمول عشان يتشارك، زي cache.
  3. ادّي الـ singletons scopes خاصة بيهمفي BackgroundService أو أي singleton محتاج يعمل شغل scoped، اعمل inject لـ IServiceScopeFactory، ونادي CreateAsyncScope لكل unit of work، واعمل resolve للـ scoped services من الـ scope ده.
  4. دوّر على الأشكال اللي الـ validation مش شايفهادوّر على AddSingleton(sp => وعلى IServiceProvider في constructors الـ singletons، وشوف بيعملوا resolve لإيه. وبعدين بص على الـ singletons اللي ماسكة transients فيها fields بتتغير.

الخلاصة

  • الـ lifetime بيحدد مين بيشارك الـ instance ولحد إمتى، والـ performance مجرد نتيجة جانبية.
  • الـ dependencies بتاعة الـ singleton بتتعمل resolve مرة واحدة من الـ root scope، وبتعيش قده مهما كان الـ lifetime بتاعها.
  • الـ DbContext المحبوس بيبقى مشترك بين كل الـ requests: الـ calls اللي في نفس الوقت بترمي exception، والداتا اللي بيعملها tracking بتبقى قديمة، والـ memory بتزيد.
  • الـ Development بيرفض الـ captive اللي في الـ constructor وقت الـ startup، والـ production مش بيشيّك على حاجة إلا لو شغّلت ValidateScopes.
  • الـ factories والـ IServiceProvider والـ transients اللي فيها state بيعدّوا من checks الـ startup، فخلّي عمر كل service عمره ما يزيد عن عمر الحاجات اللي معتمدة عليها.

📚 المصادر

  1. Service lifetimes (dependency injection) — Microsoft Learn
  2. Dependency injection guidelines — Microsoft Learn
  3. Dependency injection in ASP.NET Core — Microsoft Learn
  4. Dependency injection in .NET: Scope validation — Microsoft Learn
  5. DbContext lifetime, configuration, and initialization — EF Core, Microsoft Learn

التعليقات (0)