Search code examples
c#asp.net-corestartupbackground-taskihostedservice

Run an IHostedService function during the Start of application but only once


I have a need to run a function only once every time the application start (the function checks for a particular Mongo collection in my DB and insert in documents that are predefined by myself).

IHostedService/BackgroundService seemingly was able to do the job. I just need to inject the service into my Startup.cs file.

However, I was wondering if there are anyways that I can gracefully achieve this task since IHostedService is really made to implement more of a cron job (a task that needs to run in an interval of time say, every 30 minutes).

Thank you.


Solution

  • I was able to achieve what I want just by using IHostedService.

    protected override async Task ExecuteAsync(CancellationToken cancellationToken)
            {
                //logic
            }
    

    And in Startup.cs this is how I register my service.

    AddSingleton<IHostedService, myService>
    

    I ran my application and it debug into the AddSingleton line and only run the ExecuteAsync function once. So that is my solution.