簡體   English   中英

.NET Core 2.1。 像控制器一樣在啟動時運行服務

[英].NET Core 2.1. Run service on startup like controller

我需要在應用程序開始運行后立即運行MyService。 我想像控制器中那樣自動解析DI,所以不必像現在在Program.cs中那樣獲得服務: var someDependency = services.GetRequiredService<ISomeDependency>

private readonly ISomeDependency some;
public void Here()
{
    MyService(some);
}

嘗試IHostedService- https: //blogs.msdn.microsoft.com/cesardelatorre/2017/11/18/implementing-background-tasks-in-microservices-with-ihostedservice-and-the-backgroundservice-class-net-core-2 -x /在我們所有的自托管站點中均可使用。

    internal abstract class HostedService : IHostedService
{
    private CancellationTokenSource _cts;
    private Task _executingTask;

    protected ILogger Logger { get; }

    protected HostedService(ILoggerFactory loggerFactory)
    {
        Logger = loggerFactory.CreateLogger(GetType());
    }

    public virtual 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);

        Logger.LogInformation($"{GetType().Name} started");

        // If the task is completed then return it, otherwise it's running
        return _executingTask.IsCompleted ? _executingTask : Task.CompletedTask;
    }

    public virtual 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));

        Logger.LogInformation($"{GetType().Name} stopped");

        // 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);
}

internal class MyService : HostedService
{
    private readonly ISomeDependency _someDependency;

    public MyService(ISomeDependency someDependency)
    {
        _someDependency = someDependency;
    }

    protected override async Task ExecuteAsync(CancellationToken cancellationToken)
    {
        while (!cancellationToken.IsCancellationRequested)
        {
            _someDependency.DoSmths();
        }
    }
}

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IHostedService, MyService>();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM