How do I get a reference to an IHostedService via Dependency Injection in ASP.NET Core?

Current workaround from mentioned git page:

services.AddSingleton<YourServiceType>();
services.AddSingleton<IHostedService>(p => p.GetRequiredService<YourServiceType>());

Or, if your service implements some other interfaces:

services.AddSingleton<YourServiceType>();    
services.AddSingleton<IYourServiceType>(p => p.GetRequiredService<YourServiceType>());
services.AddSingleton<IHostedService>(p => p.GetRequiredService<YourServiceType>());

This creates your service as hosted (runs and stops at host’s start and shutdown), as well as gets injected as depedency wherever you require it to be.

Update:

I don’t see this solution as a “workaround” anymore.

Instead, I would describe it this way: hosted component and a regular service are entities of different types, each one serving its own purpose.

The solution above, however, allows one to combine them, registering a hosted component as a service, which can be used in the dependency resolution chain.

Which is awesome.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)