2 回答

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超6個(gè)贊
這只是在 .NET Core 2.0 中不可用嗎?
ServiceCollectionHostedServiceExtensions.AddHostedService(IServiceCollection) 方法如 API 參考中所示
適用于
ASP.NET Core
2.1
但是源代碼可以在 GitHub 上找到。您可以輕松地在那里查看并將本地版本復(fù)制到您的 2.0 項(xiàng)目
namespace Microsoft.Extensions.DependencyInjection
{
public static class ServiceCollectionHostedServiceExtensions
{
/// <summary>
/// Add an <see cref="IHostedService"/> registration for the given type.
/// </summary>
/// <typeparam name="THostedService">An <see cref="IHostedService"/> to register.</typeparam>
/// <param name="services">The <see cref="IServiceCollection"/> to register with.</param>
/// <returns>The original <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddHostedService<THostedService>(this IServiceCollection services)
where THostedService : class, IHostedService
=> services.AddTransient<IHostedService, THostedService>();
}
}
理想情況下,您可以將項(xiàng)目更新到 2.1,以便擴(kuò)展可用。

TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超5個(gè)贊
我相信你正在尋找這個(gè)
https://blogs.msdn.microsoft.com/cesardelatorre/2017/11/18/implementing-background-tasks-in-microservices-with-ihostedservice-and-the-backgroundservice-class-net-core-2-x/
我對(duì)自己做了一個(gè) 2 小時(shí)自稱獲獎(jiǎng)的黑客馬拉松,以了解這一點(diǎn)。
https://github.com/nixxholas/nautilus
您可以在此處參考注入并從那里實(shí)現(xiàn)摘要。
許多 MVC 項(xiàng)目并不真正需要操作持久的后臺(tái)任務(wù)。這就是為什么您看不到它們通過模板融入新項(xiàng)目的原因。最好為開發(fā)人員提供一個(gè)可以點(diǎn)擊并繼續(xù)使用的界面。
此外,關(guān)于為此類后臺(tái)任務(wù)打開該套接字連接,我還沒有為此建立解決方案。據(jù)我所知/所做的,我只能將有效負(fù)載廣播到連接到我自己的 socketmanager 的客戶端,所以你必須在別處尋找。如果 IHostedService 中有任何關(guān)于 websocket 的信息,我肯定會(huì)發(fā)出嗶嗶聲。
好吧,無論如何,這就是發(fā)生的事情。
把它放在你的項(xiàng)目中的某個(gè)地方,它更像是一個(gè)讓你重載以創(chuàng)建自己的任務(wù)的界面
/// Copyright(c) .NET Foundation.Licensed under the Apache License, Version 2.0.
/// <summary>
/// Base class for implementing a long running <see cref="IHostedService"/>.
/// </summary>
public abstract class BackgroundService : IHostedService, IDisposable
{
protected readonly IServiceScopeFactory _scopeFactory;
private Task _executingTask;
private readonly CancellationTokenSource _stoppingCts =
new CancellationTokenSource();
public BackgroundService(IServiceScopeFactory scopeFactory) {
_scopeFactory = scopeFactory;
}
protected abstract Task ExecuteAsync(CancellationToken stoppingToken);
public virtual Task StartAsync(CancellationToken cancellationToken)
{
// Store the task we're executing
_executingTask = ExecuteAsync(_stoppingCts.Token);
// If the task is completed then return it,
// this will bubble cancellation and failure to the caller
if (_executingTask.IsCompleted)
{
return _executingTask;
}
// Otherwise it's running
return Task.CompletedTask;
}
public virtual async Task StopAsync(CancellationToken cancellationToken)
{
// Stop called without start
if (_executingTask == null)
{
return;
}
try
{
// Signal cancellation to the executing method
_stoppingCts.Cancel();
}
finally
{
// Wait until the task completes or the stop token triggers
await Task.WhenAny(_executingTask, Task.Delay(Timeout.Infinite,
cancellationToken));
}
}
public virtual void Dispose()
{
_stoppingCts.Cancel();
}
}
這是您實(shí)際使用它的方法
public class IncomingEthTxService : BackgroundService
{
public IncomingEthTxService(IServiceScopeFactory scopeFactory) : base(scopeFactory)
{
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
using (var scope = _scopeFactory.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<NautilusDbContext>();
Console.WriteLine("[IncomingEthTxService] Service is Running");
// Run something
await Task.Delay(5, stoppingToken);
}
}
}
}
如果你注意到了,那里有一個(gè)獎(jiǎng)金。您必須使用服務(wù)范圍才能訪問數(shù)據(jù)庫操作,因?yàn)樗菃卫摹?/p>
注入你的服務(wù)
// Background Service Dependencies
services.AddSingleton<IHostedService, IncomingEthTxService>();
- 2 回答
- 0 關(guān)注
- 242 瀏覽
添加回答
舉報(bào)