
فخ الـ Captive Dependency: لما الـ Singleton يمسك في Scoped service
- كاتب موثّق
- .NET 10
محتويات المقال
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". ومحدش لمس كود الداتابيز أصلًا.
الفكرة الغلط الشائعة
PriceService ماسكة ShopDb، والـ DbContext مليان state: change tracker، والعملية اللي شغالة دلوقتي، و connection. والـ guidelines بتاعة Microsoft بتقول عكس الفكرة دي: استخدم singleton بس للـ service اللي الـ state بتاعها غالي تعمله أو معمول عشان يتشارك، وابعد عنه للـ services اللي مفيهاش state، لأنها رخيصة جدًا كـ transient.
اللي بيحصل فعلًا
الـ singleton بيتبني مرة واحدة، بكل اللي طلبه
المحبوسة جاية من الـ root scope، مش من 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
ShopDb، وفيه Products:
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;}var builder = WebApplication.CreateBuilder(args);builder.Services.AddDbContext<ShopDb>();// No longer-lived than its shortest-lived dependencybuilder.Services.AddScoped<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){ // A fresh ShopDb per request, disposed when the request ends public async Task<decimal?> GetAsync(int id) => (await db.Products.FindAsync(id))?.Price;}AddHostedService بيسجّلها singleton. ماتعملش inject للـ context هناك. اعمل inject لـ IServiceScopeFactory واعمل scope لكل unit of work:
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 بيمسك إيه
WebApplication.CreateBuilder بيشغّل اتنين checks: الـ ValidateScopes بيرفض أي scoped service بتتعمل resolve من الـ root أو بيستخدمها singleton، والـ ValidateOnBuild بيبني كل التسجيلات وقت الـ startup. وفي تجربة على .NET 10، الاتنين مع بعض بيمسكوا أشكال وبيفوّتوا أشكال:
IServiceProvider متعمله inject | ||
تطبقها إزاي في مشروعك
شغّل الاتنين checks برّه الـ Development فعّل ValidateScopesوValidateOnBuildفي الـ staging وفي الـ integration tests، أو في كل الـ environments. ساعتها أي captive في constructor هيفشل قبل ما أي traffic يوصل.خلّي الـ scoped هو الأساس جنب الـ requests والداتابيز الـ services اللي بتستخدم DbContext، والـ repositories، وأي حاجة شايلة داتا خاصة بـ user، كلها scoped. وخلّي الـ service تبقى singleton بس لو هي thread-safe وشايلة state معمول عشان يتشارك، زي cache.ادّي الـ singletons scopes خاصة بيهم في BackgroundServiceأو أي singleton محتاج يعمل شغل scoped، اعمل inject لـIServiceScopeFactory، وناديCreateAsyncScopeلكل unit of work، واعمل resolve للـ scoped services من الـ scope ده.دوّر على الأشكال اللي الـ 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 عمره ما يزيد عن عمر الحاجات اللي معتمدة عليها.
📚 المصادر
Service lifetimes (dependency injection) — Microsoft Learn Dependency injection guidelines — Microsoft Learn Dependency injection in ASP.NET Core — Microsoft Learn Dependency injection in .NET: Scope validation — Microsoft Learn DbContext lifetime, configuration, and initialization — EF Core, Microsoft Learn
التعليقات (0)