x.For<IUnitOfWork>().HybridHttpOrThreadLocalScoped().Use<MyContext>();
سؤال: برای سایر حالات چطور؟ در یک برنامهی ویندوزی کنسول یا سرویس ویندوز که Http Scoped در آن معنا ندارد چکار باید کرد؟
پاسخ: در اینجا حداقل دو راه حل وجود دارد:
الف) استفاده از nested containers
using (var container = ObjectFactory.Container.GetNestedContainer()) { var uow = container.GetInstance<IUnitOfWork>(); }
در مثال فوق، پس از پایان کار قطعهی using نوشته شده، به صورت خودکار کلیه اشیاء IDisposable یافت شده و Dispose میشوند.
ب) نگاهی به پشت صحنهی متد DisposeAndClearAll
اگر اشیاء IDisposable شما با طول عمر HybridHttpOrThreadLocalScoped معرفی شده باشند (و Transient نباشند)، با دستور ذیل چه در برنامههای ویندوزی و چه در برنامههای وب، کلیهی آنها یافت شده و به صورت خودکار Dispose میشوند:
new HybridLifecycle().FindCache(null).DisposeAndClear();
بنابراین به صورت خلاصه
اگر طول عمر شیء IDisposable مدنظر به صورت هیبرید تعریف شدهاست، از متد DisposeAndClear موجود در HybridLifecycle میتوان استفاده کرد. اگر طول عمر شیء IDisposable مورد استفاده، معمولی است و هیچ نوع caching خاصی برای آن درنظر گرفته نشدهاست، میتوان از روش nested containers برای رها سازی خودکار منابع آن کمک گرفت.