After reading this post I can understand the differences between AddTransient
,AddScoped
and AddSingleton
however, I am unable to see the practical usage of each of them.
My understanding is
AddTransient
Creates a new instance every time when the client asks for it.
services.AddTransient<IDataAccess, DataAccess>();
will return a new DataAccess object every time a client code asks for it. More likely a constructor.
Usage of AddTransient
In cases when we have to access a database to read and update it and destroy the access object (DataAccess) its best to use AddTransient
- Not sure about the thread safty.
AddScoped
Creates a new instance for each http web request.
Usage of AddScoped
services.AddScoped<ShoppingCart>(serviceProvider => ShoppingCart.GetShoppingCart(serviceProvider));
this mean each web request will be having its own shopping cart instance which intern means each user / client will be having its own shoping cart instance for that http web request.
AddSingleton
Create single instance for all the http web requests.
Usage of AddSingleton
Found this code in an sample application but I dont understand how it is being useful.
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
Can someone please give a decent practical example when to use AddSingleton and check if my understanding of AddTransient and AddScoped is correct?