I am attempting to write a customer order tracker using Blazor Server.
What I'd like to do is launch on the background an order management service for every new order created. The service would keep track of various live information associated with the order, and it should be disposed of when the order is completed.
I am able to do that through registering the service as:
services.AddTransient();
I can then dependency-inject this into a razor component:
@inject OrderManagementService om_service
This creates a new instance for each order, which is good. The problem is that I can't expect the user to keep the page open in order to keep the the Transient service's scope alive.
From my observation, the instance continues to run, but its lifetime is not well-defined. It could terminate indefinitely soon (not long enough to finish the job), or run indefinitely long (thus robbing the server of resources). As I have no reference to it.
How can this problem be solved? If Transient services are not the solution, then what would it be?
Thank you!
Check out hosted background services in .NET Core, sounds like it could work for you.
Hosted background services continue running on your server even if the user navigates away from your site. You could have an OrderManager
hosted service that guides each order through the process and keeps the order status updated in the database, email the user status updates, or push changes to the front-end.