I’m using ASP.Net and I have dependency injection setup in a way that IRepository is added as scoped. Everything works fine in request response scenario.
But I also added BackgroudService which is executed once every minute and need to take some fresh data. In order to do that I can’t register IRepository as a singleton, I would like it to be created each time it is needed. What is the best option to do it in asp.net using built in IoC container?
2
Answers
Inject
IServiceProvider
instead of the repository. When needed, manually create a scope by calling theCreateScope
(withusing
to dispose the service scope when leaving scope) and then useGetRequiredService
to get an instance of yourIRepository
implementation.This is all detailed with an example in Microsoft’s page on background tasks and hosted services in ASP.NET Core. Example from that page:
I would recommend using existing solutions for scheduled background tasks, e.g. Hangfire.
In scenarios like yours, I prefer to register a separate SchedulerService that controls tasks that must be started on a schedule or repeated every time interval, e.g., run a task each minute, as in your case.
Here is an example from my project:
The simple implementation Scheduler worker where you can call your methods
And here is the registration of all the services in Program.cs: