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?
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With