Skip to content

.NET - Background Worker

License

Notifications You must be signed in to change notification settings

dimitrietataru/netcore-background-worker

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

26 Commits
 
 
 
 
 
 
 
 

Repository files navigation

.NET - Background Worker

Install

PM> Install-Package Microsoft.Extensions.Hosting -Version 5.0.0

Structure

public class Worker : BackgroundService
{
    private readonly IServiceProvider serviceProvider;

    public Worker(IServiceProvider serviceProvider)
    {
        this.serviceProvider = serviceProvider;
    }

    protected override async Task ExecuteAsync(CancellationToken cancellationToken)
    {
        using var scope = serviceProvider.CreateScope();
        var type = scope.ServiceProvider.GetRequiredService<IType>();
    
        while (!cancellationToken.IsCancellationRequested)
        {
            // ..
        }
    }
}

Setup - Worker Service

public class Program
{
    public static async Task Main(string[] args)
    {
        await Host
            .CreateDefaultBuilder(args)
            .ConfigureServices((_, services) =>
                {
                    services.AddTransient<IType, Type>();
                    services.AddHostedService<Worker>();
                })
            .Build()
            .RunAsync()
            .ConfigureAwait(continueOnCapturedContext: false);
    }
}

Setup - WebApp Worker

public class Program
{
    public static async Task Main(string[] args)
    {
        await Host
            .CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>())
            .Build()
            .RunAsync()
            .ConfigureAwait(continueOnCapturedContext: false);
    }
}

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // ..

        services.AddScoped<IType, Type>();
        services.AddHostedService<Worker>();

        // ..
    }
}