İçindeki kapsamlı hizmetleri kullanma BackgroundService

IHostedServiceUzantı yöntemlerinden herhangi birini kullanarak uygulama kaydettiğinizde, AddHostedService hizmet tek bir olarak kaydedilir. Kapsamlı bir hizmete bağlanmak istediğiniz senaryolar olabilir. Daha fazla bilgi için bkz. .net 'e bağımlılık ekleme: hizmet yaşam süreleri.

Bu öğreticide şunların nasıl yapıldığını öğreneceksiniz:

İpucu

".NET 'teki çalışanlar" örnek kaynak kodu, indirmek üzere Samples Browser 'da bulunabilir. Daha fazla bilgi için bkz. kod örneklerine gözatıyor: .net Içindeki çalışanlar.

Önkoşullar

Yeni proje oluşturma

Yeni bir Çalışan Hizmeti projesi oluşturmak Visual Studio Dosya Yeni Proje... seçeneğini > > belirtirsiniz. Yeni proje oluştur iletişim kutusunda "Çalışan Hizmeti" araması yazın ve Çalışan Hizmeti şablonunu seçin. .NET CLI kullanmak yerine sık kullanılan terminali bir çalışma dizininde açın. komutunu dotnet new çalıştırın ve yerine <Project.Name> istediğiniz proje adını yazın.

dotnet new worker --name <Project.Name>

.NET CLI yeni çalışan hizmeti projesi komutu hakkında daha fazla bilgi için bkz. dotnet new worker.

İpucu

Visual Studio Code kullanıyorsanız tümleşik terminalden .NET CLI komutlarını çalıştırabilirsiniz. Daha fazla bilgi için bkz. Visual Studio Code: Tümleşik Terminal.

Kapsamlı hizmetler oluşturma

İçindeki kapsamlı hizmetleri kullanmak için BackgroundService bir kapsam oluşturun. Barındırılan hizmet için varsayılan olarak kapsam oluşturulmaz. Kapsamlı arka plan hizmeti, arka plan görevinin mantığını içerir.

namespace App.ScopedService;

public interface IScopedProcessingService
{
    Task DoWorkAsync(CancellationToken stoppingToken);
}

Önceki arabirim tek bir yöntemi tanımlar DoWorkAsync . Varsayılan uygulamayı tanımlamak için:

  • Hizmet zaman uyumsuz. DoWorkAsyncYöntemi bir döndürür Task . Tanıtım amacıyla, yöntemde on saniyelik bir gecikme beklenir DoWorkAsync .
  • ILoggerHizmete eklenen bir.:
namespace App.ScopedService;

public class DefaultScopedProcessingService : IScopedProcessingService
{
    private int _executionCount;
    private readonly ILogger<DefaultScopedProcessingService> _logger;

    public DefaultScopedProcessingService(
        ILogger<DefaultScopedProcessingService> logger) =>
        _logger = logger;

    public async Task DoWorkAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            ++ _executionCount;

            _logger.LogInformation(
                "{ServiceName} working, execution count: {Count}",
                nameof(DefaultScopedProcessingService),
                _executionCount);

            await Task.Delay(10_000, stoppingToken);
        }
    }
}

Barındırılan hizmet, yöntemini çağırmak için kapsamlı arka plan hizmetini çözümlemek üzere bir kapsam oluşturur DoWorkAsync . DoWorkAsync şunu döndürür Task ExecuteAsync :

Çalışan sınıfını yeniden yazın

Var olan Worker sınıfı aşağıdaki C# koduyla değiştirin ve dosyayı Scopedbackgroundservice. cs olarak yeniden adlandırın:

namespace App.ScopedService;

public sealed class ScopedBackgroundService : BackgroundService
{
    private readonly IServiceProvider _serviceProvider;
    private readonly ILogger<ScopedBackgroundService> _logger;

    public ScopedBackgroundService(
        IServiceProvider serviceProvider,
        ILogger<ScopedBackgroundService> logger) =>
        (_serviceProvider, _logger) = (serviceProvider, logger);

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation(
            $"{nameof(ScopedBackgroundService)} is running.");

        await DoWorkAsync(stoppingToken);
    }

    private async Task DoWorkAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation(
            $"{nameof(ScopedBackgroundService)} is working.");

        using (IServiceScope scope = _serviceProvider.CreateScope())
        {
            IScopedProcessingService scopedProcessingService =
                scope.ServiceProvider.GetRequiredService<IScopedProcessingService>();

            await scopedProcessingService.DoWorkAsync(stoppingToken);
        }
    }

    public override async Task StopAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation(
            $"{nameof(ScopedBackgroundService)} is stopping.");

        await base.StopAsync(stoppingToken);
    }
}

Yukarıdaki kodda, açık bir kapsam oluşturulur ve IScopedProcessingService uygulama bağımlılık ekleme hizmeti sağlayıcısından çözümlenir. Çözümlenen hizmet örneği kapsamlıdır ve DoWorkAsync yöntemi bekletildi.

Şablon programı. cs dosya Içeriğini aşağıdaki C# koduyla değiştirin:

using App.ScopedService;

using IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        services.AddHostedService<ScopedBackgroundService>();
        services.AddScoped<IScopedProcessingService, DefaultScopedProcessingService>();
    })
    .Build();

await host.RunAsync();

Hizmetler ' de kaydedilir IHostBuilder.ConfigureServices (program. cs). Barındırılan hizmet AddHostedService uzantı yöntemiyle kaydedilir.

Hizmetleri kaydetme hakkında daha fazla bilgi için bkz. .net 'Te bağımlılık ekleme.

Hizmet işlevselliğini doğrulama

Uygulamayı Visual Studio 'dan çalıştırmak için F5 ' i seçin veya hata > ayıklamayı Başlat menü seçeneğini belirleyin. .NET CLı kullanıyorsanız, dotnet run çalışma dizininden komutunu çalıştırın:

dotnet run

.NET CLı Run komutu hakkında daha fazla bilgi için bkz. DotNet Run.

Uygulamanın birkaç yürütme sayısı artışlarını oluşturmak için bir bit çalışmasına izin verin. Aşağıdakine benzer bir çıktı görürsünüz:

info: App.ScopedService.ScopedBackgroundService[0]
      ScopedBackgroundService is running.
info: App.ScopedService.ScopedBackgroundService[0]
      ScopedBackgroundService is working.
info: App.ScopedService.DefaultScopedProcessingService[0]
      DefaultScopedProcessingService working, execution count: 1
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: .\scoped-service
info: App.ScopedService.DefaultScopedProcessingService[0]
      DefaultScopedProcessingService working, execution count: 2
info: App.ScopedService.DefaultScopedProcessingService[0]
      DefaultScopedProcessingService working, execution count: 3
info: App.ScopedService.DefaultScopedProcessingService[0]
      DefaultScopedProcessingService working, execution count: 4
info: Microsoft.Hosting.Lifetime[0]
      Application is shutting down...
info: App.ScopedService.ScopedBackgroundService[0]
      ScopedBackgroundService is stopping.

Uygulamayı uygulamanın içinde çalıştırıyorsanız hata Visual Studio Hata Ayıklamayı > Durdur... öğesini seçin. Alternatif olarak, iptali işaret etmek için konsol penceresinden Ctrl + C'yi seçin.

Ayrıca bkz.