Tutorials Design Patterns in C#

Hosted Service Pattern — Complete Guide

Hosted Service Pattern — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of Design Patterns in C# on Toolliyo Academy.

On this page

Design Patterns in C# · Lesson 58 of 69

Hosted Service Pattern

GoF Core ✓Enterprise ✓Cloud & Craft

Cloud & Craft · 3 — Microservices & interviews · ~10 min · Module 7: ASP.NET Core Architecture Patterns

What is this?

IHostedService/BackgroundService runs long-running work inside the host — queues, relays, periodic jobs.

Why should you care?

ShopNest outbox relay and cache warmers need a process lifetime hook, not a one-off console.

See it live — copy this example

Paste into a C# console or class library project and run dotnet run.

public sealed class OutboxRelayService : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            Console.WriteLine("relay tick");
            await Task.Delay(1000, stoppingToken);
        }
    }
}
// builder.Services.AddHostedService<OutboxRelayService>();

Run Example »

Edit the code below and click Run to see the result in Toolliyo’s live editor.

Code
Result

What happened?

  • BackgroundService loops until cancellation.
  • Respect stoppingToken.
  • For multi-instance jobs, combine with leader election or queue competing consumers.

Practice next

  1. Add a hosted service to ShopNest API.
  2. Honor CancellationToken.
  3. Scope DbContext per iteration carefully.
  4. Process outbox batch each tick.
  5. Add graceful delay on shutdown.

Remember

Background work in-host. Cancel cleanly. Mind multi-instance.

ShopNest outbox hosted service

API host runs relay loop.

Outcome: Events publish without a separate worker binary (small scale).

Interview prep for this lesson

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

Mid PDF Detailed
Abstract Factory (LoggerFactory):?
Short answer: The LoggerFactory class defines a factory method CreateLogger that returns an ILogger object. This is a generic interface for creating various logger types without specifying the concrete class directly. Re…
Mid PDF Detailed
Redo Functionality:?
Short answer: You can extend the system by adding redo functionality. After an undo operation, you could store the undone command in a separate stack and allow users to redo the previous undo operation. Real-world exampl…
Mid PDF Detailed
Abstract Expression (IExpression):?
Short answer: The IExpression interface declares an Interpret method, which is the core of the interpreter pattern. This method is used to interpret and evaluate expressions. public interface IExpression Example code { i…
Mid PDF Detailed
Mediator (ChatMediator):?
Short answer: The mediator manages communication between the users. It maintains a list of all users and broadcasts messages to all other users when one user sends a message. This keeps the users from directly knowing ab…
Mid PDF Detailed
Component (ICoffee):?
Short answer: This is the base interface that defines the common methods for the Cost() and Description() that every coffee component will implement. public interface ICoffee Example code { double Cost(); string Descript…
Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

Design Patterns in C#
Course syllabus

Design Patterns in C# Tutorial

Module 1: Creational Design Patterns
Module 2: Structural Design Patterns
Module 3: Behavioral Design Patterns
Module 4: Enterprise Design Patterns
Module 5: Modern Enterprise Patterns
Module 6: Microservices & Cloud Patterns
Module 7: ASP.NET Core Architecture Patterns
Module 8: Interview & System Design
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