Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start a service (`IServiceCollection`) at startup

I have a singleton service I want running at startup rather waiting for some Controller to construct the service via Dependency Injection.

The service processes data from a service bus and it doesn't seem to right rely on client traffic. What is the cleanest way to initialise it?

like image 431
KCD Avatar asked Sep 02 '25 16:09

KCD


1 Answers

Usually you instantiate the service normally, then pass a reference of it to AddSingleton() method.

var someRepository = new SomeRepository(/*pass in configuration and dependencies*/);

// pass instance of the already instantiated service
services.AddSingleton<ISomeRespository>(someRepository);

Edit

Or a warmup extension method:

public static class WarmupServiceProviderExtensions
{
    public static void WarmUp(this IServiceProvider app)
    {
        // Just call it to resolve, no need to safe a reference
        app.RequestService<ISomeRepository>();
    }
}

and in your Startup.cs

public void Configure(IServiceProvider app) 
{
    app.UseXyz(...);

    // warmup/initailize your services
    app.WarmUp();
}
like image 135
Tseng Avatar answered Sep 05 '25 04:09

Tseng



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!