.NET Core 2.1。在启动时运行服务,如控制器

时间:2018-02-20 07:37:33

标签: .net core

我需要在应用程序开始运行后立即运行MyService。我希望DI在控制器中自动解决,所以我不需要像在Program.cs中那样获得服务:var someDependency = services.GetRequiredService<ISomeDependency>

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

1 个答案:

答案 0 :(得分:0)

尝试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>();
    }
}