Tutorials ASP.NET Core Complete Tutorial (ShopNest)

Background Services and Hosted Services in ASP.NET Core

Learn Background Services and Hosted Services in ASP.NET Core in our free ASP.NET Core Complete Tutorial (ShopNest) series. Step-by-step explanations, examples, and interview tips on Toolliyo Academy.

On this page
Background Services and Hosted Services in ASP.NET Core — ShopNest
Article 47 of 75 · Module 6: Advanced Architecture · ShopNest Email Queue Processor
Target keyword: background services asp.net core · Read time: ~32 min · .NET: 8 / 9 · Project: ShopNest Email Queue Processor

Introduction

ShopNest sends order confirmation emails and nightly reports without blocking HTTP requests — BackgroundService and Channel<T> queues process work off the request thread.

After this article you will

  • Implement BackgroundService and IHostedService
  • Use Channel for producer/consumer email queue
  • Create scopes with IServiceScopeFactory for DbContext
  • Compare Hangfire and Quartz.NET
  • Monitor background work with health checks

Prerequisites

Concept deep-dive

public class EmailQueueService : BackgroundService
{
    private readonly Channel<EmailMessage> _channel;
    private readonly IServiceScopeFactory _scopes;

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await foreach (var email in _channel.Reader.ReadAllAsync(stoppingToken))
        {
            using var scope = _scopes.CreateScope();
            var sender = scope.ServiceProvider.GetRequiredService<IEmailSender>();
            await sender.SendAsync(email, stoppingToken);
        }
    }

    public async Task EnqueueAsync(EmailMessage msg) =>
        await _channel.Writer.WriteAsync(msg);
}

Scoped services: Never inject DbContext into singleton BackgroundService — create scope per message. Hangfire: persistent jobs with dashboard. Quartz: cron-style scheduling.

Hands-on — ShopNest Email Queue Processor

  1. EmailQueueService + Channel bounded capacity 1000.
  2. OrderPlacedEvent handler enqueues confirmation email.
  3. DailyReportBackgroundService runs at 2 AM UTC.
  4. Health check: queue depth under threshold.

Common errors & best practices

  • Singleton holding scoped DbContext — ObjectDisposedException.
  • No cancellation — app shutdown hangs on long work.
  • Unbounded channel — memory exhaustion under spike.

Interview questions

Q: IHostedService vs BackgroundService?
A: BackgroundService abstracts ExecuteAsync loop — easier for long-running workers.

Q: Why Channel?
A: Thread-safe producer/consumer queue between HTTP and background worker.

Q: Hangfire when?
A: Need persistent retries, dashboard, scheduled jobs across restarts.

Summary

  • BackgroundService runs outside HTTP pipeline
  • Channel queues decouple request from email send
  • IServiceScopeFactory resolves scoped DbContext per job
  • Hangfire/Quartz for enterprise scheduling needs

Previous: Repository Pattern — Deep Dive
Next: Caching in ASP.NET Core

FAQ

Azure Functions instead?

For serverless burst workloads; BackgroundService fine in App Service.

Multiple instances?

Use distributed queue (Service Bus) so only one consumer processes each message.

Interview prep for this lesson

Practice these questions aloud after reading—each links to a full structured answer.

Junior Detailed
Explain CLR & types in the context of ASP.NET Core Complete Tutorial (ShopNest).
Short answer: The CLR loads assemblies, manages memory (GC), and JIT-compiles IL to native code. Value types live on the stack or inline in objects; reference types live on the heap with GC tracking. Real-world example (…
Mid Detailed
What are common mistakes teams make with ASP.NET Core when using ASP.NET Core Complete Tutorial (ShopNest)?
Short answer: ASP.NET Core is cross-platform, uses Kestrel, middleware pipeline, and built-in DI. Requests flow: routing → middleware → endpoints → filters → action. Real-world example (ShopNest) In a ShopNest .NET servi…
Senior Detailed
How would you debug a production issue related to EF Core in a ASP.NET Core Complete Tutorial (ShopNest) application?
Short answer: EF Core maps C# entities to tables, tracks changes, and translates LINQ to SQL. Migrations version schema; Include/ThenInclude load graphs. Real-world example (ShopNest) In a ShopNest .NET service, explain…
Junior Detailed
Describe a real-world scenario where Testing mattered in a ASP.NET Core Complete Tutorial (ShopNest) project.
Short answer: Interviewers want a crisp definition, a practical example from your projects, and awareness of trade-offs—not textbook dumps. Explain a bit more How to structure your answer (60–90 seconds) Define Testing i…
Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

ASP.NET Core Complete Tutorial (ShopNest)
Course syllabus
Module 1: Foundations
Module 2: Entity Framework Core
Module 3: Dependency Injection & Middleware
Module 4: Authentication & Security
Module 5: Web API
Module 6: Advanced Architecture
Module 7: Testing
Module 8: Deployment & DevOps
Module 9: Real-World Projects
Module 10: Advanced Topics
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details