ویرگول
ورودثبت نام
mohammad mhammadi
mohammad mhammadi
خواندن ۱ دقیقه·۲ سال پیش

singleTone vs Transient vs Scoped and HostedService

  • Transient — Services are created each time they are requested. It gets a new instance of the injected object, on each request of this object. For each time you inject this object is injected in the class, it will create a new instance.
  • Scoped — Services are created on each request (once per request). This is most recommended for WEB applications. So for example, if during a request you use the same dependency injection, in many places, you will use the same instance of that object, it will make reference to the same memory allocation.
  • Singleton — Services are created once for the lifetime of the application. It uses the same instance for the whole application.
  • transient > scoped > singleton
  • for using 'scoped' in 'singleton' we can use 'serviceprovider'
using(varscope=this.serviceProvider.CreateScope())
{
();"> varscopeService=scope.ServiceProvider.GetRequiredService();
Console.WriteLine("scopeforExecuteAsync2");
awaitscopeService.scopeTask(stoppingToken);
}
  • we cant use 'transient' in 'singleton' or 'scoped'
  • Hostedservice life time is singleton
  • there is no diffrrenc between hostedService and backgroundService , they all working parallel
hostedserviceScopedTransientsingletonelifetime in c
شاید از این پست‌ها خوشتان بیاید