I learned that the preferred ASP.NET-Core-way for background tasks is a hosted service.
Is there any way to pass the (user) session to this background worker? Usually the session is part of the HttpContext
which will not be available in the background task...
I know that I could persist data by writing to the database but I'd also like to cache some data in memory.
If this is all happening in-process, then you should be able to just pass the ISession
object directly to your background service and have it interact with the user’s session without the user’s HttpContext having to be around.
The default session implementation is using the distributed cache to persist the information stored in the session. Each session object is then only interacted by with a session key that is stored in a user cookie. When the session object is being created, no direct or indirect reference to the HttpContext is being passed. The session store itself also does not access the HttpContext in some other way. The distributed cache itself is also independent of the context and also the DI service scope.
So at least in theory, this should work just fine. You can use the ISession
object to modify the session and the next time the user makes a request with their session id, the updated information will be there waiting for them.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments