我正在尝试将IHostedService
的实例注入另一个IHostedService
,但在Run()
调用Program.cs
时,我总是遇到上述错误。
基本上,我有两项服务:
public class CacheService : HostedService
{
public CacheService()
{
}
/...
}
public class ClientService : HostedService
{
private CacheService _cacheService;
public ClientService(CacheService cacheService)
{
_cacheService = cacheService;
}
/...
}
HostedService
实施IHostedService
:
public abstract class HostedService : IHostedService
{
// Example untested base class code kindly provided by David Fowler: https://gist.github.com/davidfowl/a7dd5064d9dcf35b6eae1a7953d615e3
private Task _executingTask;
private CancellationTokenSource _cts;
public Task StartAsync(CancellationToken cancellationToken)
{
// Create a linked token so we can trigger cancellation outside of this token's cancellation
_cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
// Store the task we're executing
_executingTask = ExecuteAsync(_cts.Token);
// If the task is completed then return it, otherwise it's running
return _executingTask.IsCompleted ? _executingTask : Task.CompletedTask;
}
public async Task StopAsync(CancellationToken cancellationToken)
{
// Stop called without start
if (_executingTask == null)
{
return;
}
// Signal cancellation to the executing method
_cts.Cancel();
// Wait until the task completes or the stop token triggers
await Task.WhenAny(_executingTask, Task.Delay(-1, cancellationToken));
// Throw if cancellation triggered
cancellationToken.ThrowIfCancellationRequested();
}
// Derived classes should override this and execute a long running method until
// cancellation is requested
protected abstract Task ExecuteAsync(CancellationToken cancellationToken);
}
这是我在Startup.cs类中注入这些服务的方法:
private void AddRequiredServices(IServiceCollection services)
{
services.AddSingleton<IHostedService, CacheService>();
services.AddSingleton<IHostedService, ClientService>();
}
但是,每次运行应用程序时,都会收到CacheService
无法解决服务ClientService
的错误。我在这里做错了还是不支持?
编辑:Here是一个可以克隆的存储库,可以复制我的问题。
答案 0 :(得分:0)
由于您没有在类中注入IHostedService
接口,因此您应该将ClientService
和CacheService
直接注册到服务集合,而不是使用接口,例如。
private void AddRequiredServices(IServiceCollection services)
{
services.AddSingleton<CacheService>();
services.AddSingleton<ClientService>();
}
依赖注入器(DI)将能够解析正确的服务并将其注入到构造函数中。
当您使用接口添加服务时,DI将在构造函数中查找对接口的引用,而不是类,这就是为什么它在示例中无法注入正确的实例。
答案 1 :(得分:0)
这篇文章会有所帮助。
Injecting SimpleInjector components into IHostedService with ASP.NET Core 2.0