✅ How Scope lifetime works
I have a web api where when requesting a create endpoint, it afterwards sends an email to that person about that creation. I send email with html and for it i first check if that html was read before and then store it in a variable to improve efficiency (to not read every single time). I have that as AddTransiant, which means that besides i store that in a variable, it still has to be lost, because of a lifetime. But it doesn't, it still knows that. Can someone explain how that lifetime works?
11 Replies
Here's full code if needed
in asp.net a scope is created for request, thus for caching between different requests u would need something that has a singleton lifetime
no, sure
i added that as transiant to learn difference
but it works regardless of that type i add it
with the transient lifetime its a bit different, its used when everything that gets it injected needs its own instance.
eg if u have a transient service T and the services A and B and both get T injected, they dont share the same instance of T
singleton = one per application lifetime
scoped = one per scope the application created (in asp.net core thats per request, in another application u might create scopes differently)
transient = one per injection target
that's what i am tyring to prove but making it transient
by that login in the GetHtml this has to be always false
if (_cachedHtml != null) return _cachedHtml.Replace("[username]", username).Replace("[message]", message);
because that instanse is being renewed every single request
but it doesn't
so
EmailSender
is registered as transient?
how do u use that instance?
this class calls that
and i think i know what's the problem, since EmailWorker class isn't injected, it uses the same IEmailSender thus it doesn't create new one
right? @cap5lut
sorry was quick smoking
yep thats it
transient basically means its as long alive as the service u inject it into and background services are singletons
if u would have injected the
EmailSender
directly into the controller u would have observed that _cachedHtml
is always null
because controllers are by default transient as well
or if u would have injected the IServiceProvider
and each time u want to use EmailSender
u would request it again.
sure
thanks
if this answers ur question, please dont forget to $close the thread
Use the /close command to mark a forum thread as answered