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

后端 未结 3 844
粉色の甜心
粉色の甜心 2021-02-05 11:04

Details

I have attempted to create a background processing structure using the recommended IHostedService interface in ASP.NET 2.1. I register the service

相关标签:
3条回答
  • 2021-02-05 11:52

    This is just a slight modification to the answer by @AgentFire. This method is clearer and allows for several background hosted services in a single Web Service.

    services.AddSingleton<YourServiceType>();
    services.AddHostedService<YourServiceType>(p => p.GetRequiredService<YourServiceType>());
    
    0 讨论(0)
  • 2021-02-05 12:05

    There has been some discussion around this topic. For example, see: https://github.com/aspnet/Hosting/issues/1489. One of the problems that you'll run into is that hosted services are added as transient services (from ASP.NET Core 2.1+), meaning that resolving an hosted service from the dependency injection container will result in a new instance each time.

    The general advice is to encapsulate any business logic that you want to share with or interact from other services into a specific service. Looking at your code I suggest you implement the business logic in the AbstractProcessQueue<AbstractImportProcess> class and make executing the business logic the only concern of AbstractBackgroundProcessService<T>.

    0 讨论(0)
  • 2021-02-05 12:05

    Current workaround from mentioned git page:

    services.AddSingleton<YourServiceType>();
    services.AddSingleton<IHostedService>(p => p.GetService<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.

    0 讨论(0)
提交回复
热议问题