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

后端 未结 3 846
粉色の甜心
粉色の甜心 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 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 class and make executing the business logic the only concern of AbstractBackgroundProcessService.

提交回复
热议问题