Course Content
Modular Monolith Architecture in .NET

Lesson 0.4 ended with a list of problems we left in Fieldwork on purpose. In module 1, we make those problems happen with real requests, and then we measure what they cost us. By the end of this module, you can count how often each part of a .NET solution reaches into the others. You can name the parts that depend on each other the most, and reproduce five of Fieldwork’s bugs.

Read this lesson’s code. Don’t type it. Every method we show is Fieldwork’s own, and it is already in your folder. We run Fieldwork, send it requests and read its code. We make one temporary edit in each of lessons 1.2 and 1.3, and we write our first code in lesson 1.4, in the test project.

Before we start, think about the system you work on every day. Which two of its features would both break if one table changed shape? Which business rule is written in more than one place? And the last time it was split into projects, what decided the split: the technical role of the code, or the part of the business it serves? Write your answers down, because lesson 2.1 comes back to the third one.

Starting the Module

We work in the module-01 folder we made in lesson 0.3, the copy of source/module-00-start. Let’s open the Fieldwork folder inside it, in the editor and in a terminal. If you skipped lesson 0.3, make the folder now, from a terminal opened in the course folder:

Copy-Item -Recurse source\module-00-start module-01
cp -r source/module-00-start module-01

Both tabs make the same module-01 folder. Every response we show in this module comes from a fresh seed week. If you sent a POST request from Fieldwork.http in lesson 0.4, delete the database files first, so that Fieldwork seeds the week again when it starts. From the module-01/Fieldwork folder, run:

Remove-Item Fieldwork.Web\fieldwork.db*
rm -f Fieldwork.Web/fieldwork.db*

Now let’s start Fieldwork from the same folder and leave it running:

dotnet run --project Fieldwork.Web

Its log ends on the lines we saw in lesson 0.4, with Now listening on: http://localhost:5000 among them. We send this lesson’s requests from a second terminal in the same folder. Fieldwork.http holds them too, under the numbers we use here, but its comments give away each result, so we open it only after a request has run.

Endpoints and Capabilities

We listed Fieldwork’s seven controllers with their routes in lesson 0.4. Here they are again, and this time we add the part of the business each one serves:

  • CustomersController: customers, their sites and service plans, and a stand-in for the messaging provider.
  • SchedulingController: the technicians, each technician’s day, and booking, moving and cancelling visits.
  • JobsController: raising, starting, completing and cancelling jobs, and the job screen.
  • PartsController: the parts catalogue, the stock on each van, and parts used, received and reserved.
  • BillingController: invoices, the work still to invoice, and an invoice preview.
  • DashboardController: the weekly operations dashboard.
  • MobileController: the technicians’ phone app.

Six of the controllers line up with one area of the business each, and MobileController is the one we cannot place. It serves the phones, so it reaches into three areas at once: AcceptJob books a visit, CompleteJob completes a job, and GetPartAvailability checks a part before a technician promises it.

The office describes the same work in its own words: customers, scheduling, jobs, parts, billing and reporting. We divide Fieldwork by those six words for the rest of the course, and we need a name for what each of them stands for.

A capability is something the business does that a customer would recognise, such as booking a visit or invoicing a job.

Fieldwork has six: Customers, Scheduling, Jobs, Parts, Billing and Reporting. They do not map one to one onto controllers or projects. Reporting has a controller and no data of its own, and the phone app’s controller, as we saw above, serves three capabilities. In lesson 1.4, we put a number on how much each of them depends on the others.

Now write down the capabilities of the system you are paid to work on. Can you name six? Fewer is fine, and so is a longer list. In lesson 1.5, we turn your list into the map for a census of your own code.

Double Booking a Technician

Every technician in the seed works from 08:00 to 16:00, Monday to Friday. Mia Kovac already has two visits on Tuesday 8 September, from 11:00 and from 13:00. Let’s book her three more. The first two put her into the same hour, 09:00 to 10:00 on that Tuesday, through the office’s booking endpoint. The third gives her another job at 03:00 through the phone app’s endpoint. Before we send them, predict: how many appointments will Mia hold on Tuesday afterwards?

Let’s send them, requests 1 to 3, from our second terminal:

Invoke-RestMethod -Method Post -Uri http://localhost:5000/api/scheduling/bookings -ContentType application/json -Body '{"technicianId":"11111111-1111-1111-1111-000000000001","jobId":"66666666-6666-6666-6666-000000000003","startsAt":"2026-09-08T09:00:00Z","endsAt":"2026-09-08T10:00:00Z"}'
Invoke-RestMethod -Method Post -Uri http://localhost:5000/api/scheduling/bookings -ContentType application/json -Body '{"technicianId":"11111111-1111-1111-1111-000000000001","jobId":"66666666-6666-6666-6666-000000000003","startsAt":"2026-09-08T09:00:00Z","endsAt":"2026-09-08T10:00:00Z"}'
Invoke-RestMethod -Method Post -Uri http://localhost:5000/api/mobile/accept-job -ContentType application/json -Body '{"technicianId":"11111111-1111-1111-1111-000000000001","jobId":"66666666-6666-6666-6666-000000000004","startsAt":"2026-09-08T03:00:00Z","endsAt":"2026-09-08T04:00:00Z"}'
curl -s -i -X POST -H "Content-Type: application/json" -d '{"technicianId":"11111111-1111-1111-1111-000000000001","jobId":"66666666-6666-6666-6666-000000000003","startsAt":"2026-09-08T09:00:00Z","endsAt":"2026-09-08T10:00:00Z"}' http://localhost:5000/api/scheduling/bookings
curl -s -i -X POST -H "Content-Type: application/json" -d '{"technicianId":"11111111-1111-1111-1111-000000000001","jobId":"66666666-6666-6666-6666-000000000003","startsAt":"2026-09-08T09:00:00Z","endsAt":"2026-09-08T10:00:00Z"}' http://localhost:5000/api/scheduling/bookings
curl -s -i -X POST -H "Content-Type: application/json" -d '{"technicianId":"11111111-1111-1111-1111-000000000001","jobId":"66666666-6666-6666-6666-000000000004","startsAt":"2026-09-08T03:00:00Z","endsAt":"2026-09-08T04:00:00Z"}' http://localhost:5000/api/mobile/accept-job

In our run, PowerShell printed the three bookings Fieldwork sent back:

id             : 082e4d9f-bd49-4b57-8b37-c867f8f81107
technicianId   : 11111111-1111-1111-1111-000000000001
technicianName : Mia Kovac
jobId          : 66666666-6666-6666-6666-000000000003
siteId         : 33333333-3333-3333-3333-000000000003
siteLine1      : Bakehouse, Mill Lane
startsAt       : 2026-09-08T09:00:00+00:00
endsAt         : 2026-09-08T10:00:00+00:00
status         : Scheduled

id             : f6db9b33-2c84-41e6-a0ab-bc3f12fd3cf3
technicianId   : 11111111-1111-1111-1111-000000000001
technicianName : Mia Kovac
jobId          : 66666666-6666-6666-6666-000000000003
siteId         : 33333333-3333-3333-3333-000000000003
siteLine1      : Bakehouse, Mill Lane
startsAt       : 2026-09-08T09:00:00+00:00
endsAt         : 2026-09-08T10:00:00+00:00
status         : Scheduled

id             : ce34891a-d77b-4e14-b851-8a4e5dd7054a
technicianId   : 11111111-1111-1111-1111-000000000001
technicianName : Mia Kovac
jobId          : 66666666-6666-6666-6666-000000000004
siteId         : 33333333-3333-3333-3333-000000000004
siteLine1      : 27 Northgate
startsAt       : 2026-09-08T03:00:00+00:00
endsAt         : 2026-09-08T04:00:00+00:00
status         : Accepted

Fieldwork accepted all three of our bookings: two separate appointments that start at 09:00, and a third at 03:00. The third has the status Accepted, which is how the phone path marks its bookings. Your id values will differ from ours, because Fieldwork creates a new one for every booking. With -i, curl also shows the status of each response, and on our machine it printed HTTP/1.1 200 OK above each of the three bodies.

Now let’s ask for Mia’s Tuesday, with request 4:

Invoke-RestMethod "http://localhost:5000/api/scheduling/technicians/11111111-1111-1111-1111-000000000001/day?date=2026-09-08" |
    Format-Table startsAt, endsAt, status -AutoSize
curl -s "http://localhost:5000/api/scheduling/technicians/11111111-1111-1111-1111-000000000001/day?date=2026-09-08"

We get her day back as a table in PowerShell:

startsAt                  endsAt                    status
--------                  ------                    ------
2026-09-08T03:00:00+00:00 2026-09-08T04:00:00+00:00 Accepted
2026-09-08T09:00:00+00:00 2026-09-08T10:00:00+00:00 Scheduled
2026-09-08T09:00:00+00:00 2026-09-08T10:00:00+00:00 Scheduled
2026-09-08T11:00:00+00:00 2026-09-08T13:00:00+00:00 Scheduled
2026-09-08T13:00:00+00:00 2026-09-08T15:00:00+00:00 Scheduled

Mia now holds five appointments. The top three are the ones we added, and the two below them come from the seed. The one we booked at 03:00 starts five hours before her shift does. On our machine, curl printed the same five appointments, all on one line.

The Duplicated Booking Rule

Fieldwork does have a rule against booking a technician twice, and it is written in three methods. The office books through the first of them, Book, in Controllers/SchedulingController.cs:

[HttpPost("bookings")]
public async Task<ActionResult<AppointmentDto>> Book(
    [FromBody] BookAppointmentRequest request,
    CancellationToken cancellationToken)
{
    var technician = await database.Technicians
        .FirstOrDefaultAsync(
            entity => entity.Id == request.TechnicianId,
            cancellationToken);

    if (technician is null)
    {
        return NotFound(
            $"Technician {request.TechnicianId} was not found.");
    }

    if (!technician.Active)
    {
        return Conflict($"{technician.FullName} is not active.");
    }

    var job = await database.Jobs.FirstOrDefaultAsync(
        entity => entity.Id == request.JobId,
        cancellationToken);

    if (job is null)
    {
        return NotFound($"Job {request.JobId} was not found.");
    }

    var site = await database.Sites.FirstOrDefaultAsync(
        entity => entity.Id == job.SiteId,
        cancellationToken);

    if (site is null)
    {
        return NotFound($"Site {job.SiteId} was not found.");
    }

    var held = await database.Appointments
        .Where(appointment =>
            appointment.TechnicianId == request.TechnicianId
            && appointment.Status != "Cancelled")
        .ToListAsync(cancellationToken);

    var clashes = held.Any(appointment =>
        appointment.StartsAt < request.StartsAt
        && appointment.EndsAt > request.StartsAt);

    if (clashes)
    {
        return Conflict(
            $"{technician.FullName} is already booked at that time.");
    }

    var shifts = await database.Shifts
        .Where(shift => shift.TechnicianId == request.TechnicianId)
        .ToListAsync(cancellationToken);

    var insideShift = shifts.Any(shift =>
        shift.StartsAt <= request.StartsAt
        && request.EndsAt <= shift.EndsAt);

    if (!insideShift)
    {
        return Conflict(
            $"{technician.FullName} is not on shift at that time.");
    }

    var appointment = new Appointment
    {
        Id = Guid.NewGuid(),
        TechnicianId = request.TechnicianId,
        JobId = request.JobId,
        SiteId = job.SiteId,
        StartsAt = request.StartsAt,
        EndsAt = request.EndsAt,
        Status = "Scheduled"
    };

    database.Appointments.Add(appointment);

    job.Status = "Scheduled";
    job.ScheduledFor = request.StartsAt;

    await database.SaveChangesAsync(cancellationToken);

    return Ok(new AppointmentDto
    {
        Id = appointment.Id,
        TechnicianId = appointment.TechnicianId,
        TechnicianName = technician.FullName,
        JobId = appointment.JobId,
        SiteId = appointment.SiteId,
        SiteLine1 = site.Line1,
        StartsAt = appointment.StartsAt,
        EndsAt = appointment.EndsAt,
        Status = appointment.Status
    });
}

Book saves nothing until two checks pass, the clash check and the shift check. The clash check asks whether any appointment Mia holds, cancelled ones aside, runs across the start of the new one. It catches a booking that starts in the middle of an existing appointment and misses an identical one, because 09:00 < 09:00 is false. That is how our request 2 got through. A check that compared both ends of both appointments would have refused our second booking. The shift check comes second: the new appointment has to fit inside one of Mia’s shifts, or Book returns 409 Conflict.

The phone app books through AcceptJob, in Controllers/MobileController.cs, and it carries the second copy:

/// <summary>
/// The engineer takes a job on the phone and puts it in the diary
/// in the same call.
/// </summary>
[HttpPost("accept-job")]
public async Task<ActionResult<AppointmentDto>> AcceptJob(
    [FromBody] AcceptJobRequest request,
    CancellationToken cancellationToken)
{
    var technician = await database.Technicians
        .FirstOrDefaultAsync(
            entity => entity.Id == request.TechnicianId,
            cancellationToken);

    if (technician is null)
    {
        return NotFound(
            $"Technician {request.TechnicianId} was not found.");
    }

    var job = await database.Jobs.FirstOrDefaultAsync(
        entity => entity.Id == request.JobId,
        cancellationToken);

    if (job is null)
    {
        return NotFound($"Job {request.JobId} was not found.");
    }

    var held = await database.Appointments
        .Where(appointment =>
            appointment.TechnicianId == request.TechnicianId
            && appointment.Status != "Cancelled")
        .ToListAsync(cancellationToken);

    var clashes = held.Any(appointment =>
        appointment.StartsAt < request.StartsAt
        && appointment.EndsAt > request.StartsAt);

    if (clashes)
    {
        return Conflict(
            $"{technician.FullName} is already booked at that time.");
    }

    var appointment = new Appointment
    {
        Id = Guid.NewGuid(),
        TechnicianId = request.TechnicianId,
        JobId = request.JobId,
        SiteId = job.SiteId,
        StartsAt = request.StartsAt,
        EndsAt = request.EndsAt,
        Status = "Accepted"
    };

    database.Appointments.Add(appointment);

    job.Status = "Scheduled";
    job.ScheduledFor = request.StartsAt;

    await database.SaveChangesAsync(cancellationToken);

    var site = await database.Sites.FirstOrDefaultAsync(
        entity => entity.Id == job.SiteId,
        cancellationToken);

    return Ok(new AppointmentDto
    {
        Id = appointment.Id,
        TechnicianId = appointment.TechnicianId,
        TechnicianName = technician.FullName,
        JobId = appointment.JobId,
        SiteId = appointment.SiteId,
        SiteLine1 = site?.Line1 ?? string.Empty,
        StartsAt = appointment.StartsAt,
        EndsAt = appointment.EndsAt,
        Status = appointment.Status
    });
}

Its clash check is the one we read in Book, copied line for line, so the phone path misses an identical slot as well. No shift check follows it. AcceptJob never loads Mia’s shifts, and that is how it let us book her at 03:00. When we sent the same 03:00 slot to the office endpoint, Book refused it with 409 Conflict and this message: Mia Kovac is not on shift at that time.

The third copy is back in SchedulingController, in Move, the endpoint that moves a visit to a new time. Move loads the technician’s other appointments and runs the same clash check, with the same is already booked at that time message on a clash. It never looks at the shift, so of the three copies, only Book checks it.

Aggregates

Any controller in Fieldwork that can reach the appointments can add or move one, with whatever checks its author remembered to copy. That is how our booking rule came to live in three methods, and how the shift check ended up in only one of them. Domain-driven design answers this by giving a rule like ours a single owner.

An aggregate is the object that owns a consistency rule, so that the data the rule protects changes only through it.

Our booking rule has no aggregate. Each copy changes on its own, and nothing tells us when two copies stop agreeing. The nearest thing we have in Fieldwork is Invoice, in Models/Invoice.cs, the one entity with methods of its own. Its AddLine refuses a new line once the invoice is issued, and its Issue refuses to issue it twice. It still falls short of the definition, because Status and Lines are public properties that any code can change without calling those methods. Clean Architecture in .NET covers aggregates in full, and in module 6 we give the booking rule one.

Request Paths Through Fieldwork

Each of our requests went in through a controller and ended in the database. Figure 1.1 follows those paths for all seven controllers, and we redraw it in later modules as Fieldwork changes:

Fieldwork's controllers and the shared DbContextOne large frame labelled Fieldwork, one process. The six capability names, Customers, Scheduling, Jobs, Parts, Billing and Reporting, are written across the top of the frame with no lines or boxes around them, because nothing separates them yet. Below them stands a column of seven controller boxes: CustomersController, SchedulingController, DashboardController, JobsController, PartsController, BillingController and MobileController. Every controller draws an arrow to the right into one tall box labelled FieldworkDbContext. Four of them, Jobs, Parts, Billing and Mobile, also draw an arrow to the left into a box labelled FieldworkService, and FieldworkService draws an arrow under the column into FieldworkDbContext as well. FieldworkDbContext sits on a wide band labelled fieldwork.db.Fieldwork, one processCustomersSchedulingJobsPartsBillingReportingfieldwork.dbCustomersControllerSchedulingControllerDashboardControllerJobsControllerPartsControllerBillingControllerMobileControllerFieldworkServiceFieldworkDbContext
Figure 1.1. Every request in Fieldwork ends in the same DbContext and the same database file.

Four controllers go through FieldworkService on the way, the 697-line service we open in lesson 1.3. DashboardController uses only one constant from that service, its reorder level, and we leave that reference out of the figure. The six capability names at the top have no lines around them, because nothing in the code separates them yet.

Where We Are

We left Fieldwork running, and we changed no source file.

You can now name Fieldwork’s six capabilities and the controllers behind them, and make it book one technician twice into the same hour and once outside her shift. You can also find the three methods that copy our booking rule. The new terms in this lesson are capability and aggregate. In lesson 1.2, we rename one property in the shared model and count the files that stop compiling.

0% Complete