【发布时间】:2018-10-09 02:05:47
【问题描述】:
我正在尝试使用 IHostedService 创建后台服务。如果我只有一个后台服务,一切正常。当我尝试创建多个IHostedService 的实现时,只有第一个注册的实际运行。
services.AddSingleton<IHostedService, HostedServiceOne>();
services.AddSingleton<IHostedService, HostedServiceTwo>();
在上面的示例中,HostedServiceOne 上的 StartAsync 被调用,但 HostedServiceTwo 上的 StartAsync 永远不会被调用。如果我交换注册IHostedService 的两个实现的顺序(将IHostedServiceTwo 放在IHostedServiceOne 之前),那么HostedServiceTwo 上的StartAsync 会被调用,但不会被HostedServiceOne 调用。
编辑:
我被定向到以下内容:
How to register multiple implementations of the same interface in Asp.Net Core?
但这不适用于IHostedService。要使用建议的方法,我必须调用serviceProvider.GetServices<IService>();,但似乎IHostedService.StartAsync 似乎是在内部调用的。我什至不确定我会在哪里调用它来触发IHostedService.StartAsync。
【问题讨论】:
-
提供的解决方案似乎需要调用serviceProvider.GetServices。我会在哪里调用它来触发 IHostedService.StartAsync。使用单个 IHostedService 时,似乎在内部调用了 StartAsync 方法。
-
我明白了,那不是重复的,我一会儿回答这个问题
标签: c# asp.net-core asp.net-core-2.0