Every public type is a promise: once others depend on it, it's hard to change. Good library code keeps its public surface small, validates what comes in, and lets its callers choose the moving parts. Today you'll look at how the job runner does that.
Small public surface
internal makes something visible only within its own assembly, and private only within its class. Nothing is public unless you've chosen it to be. This lets you change the rest freely. An interface that's expected to grow is harder to change than a class, since adding a member breaks each implementer; a default implementation softens that.
IGreeter greeter = new Plain();
Console.WriteLine(greeter.Greet("Ana"));
Console.WriteLine(greeter.GreetAll(new[] { "Ana", "Ben" }));
interface IGreeter
{
string Greet(string name);
string GreetAll(IEnumerable<string> names) => string.Join(" ", names.Select(Greet));
}
class Plain : IGreeter
{
public string Greet(string name) => $"Hi {name}.";
}Check your prediction
Hi Ana.
Hi Ana. Hi Ben.A library also can't assume where it's called from. The job runner is a console program, but a library like it could be called from a desktop app's button handler. As Day 3's "Going further" on SynchronizationContext showed, an await there would resume on the UI thread, and a caller who blocked with .Result would deadlock. That's why library code conventionally writes await something.ConfigureAwait(false) on every await. The runner's code leaves it out, because a console app and ASP.NET Core have no context to capture, but if you turned it into a NuGet package for any kind of app, adding it would be part of making the public surface safe.
An options record
A constructor with seven numbers is unreadable, and adding an eighth breaks everyone. An options record with init properties and defaults fixes both of these problems: callers set only what they care about, and with makes variations. Validate at the door, so a bad value fails right away, with a clear message, instead of hanging later.
var defaults = new PoolOptions();
var busy = defaults with { Workers = 8 };
Console.WriteLine(defaults.Workers);
Console.WriteLine(busy.Workers);
Console.WriteLine(busy.Capacity);
try
{
new Pool(new PoolOptions { Capacity = 0 });
}
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine(e.ParamName);
}
record PoolOptions
{
public int Workers { get; init; } = 2;
public int Capacity { get; init; } = 4;
}
class Pool
{
public Pool(PoolOptions options)
{
ArgumentOutOfRangeException.ThrowIfLessThan(options.Workers, 1);
ArgumentOutOfRangeException.ThrowIfLessThan(options.Capacity, 1);
}
}Check your prediction
2
8
4
options.CapacityThe composition root
Dependencies go in through constructors, so something must build them. Do that in one place: the program's start, called the composition root. Only that code knows which concrete classes are in use, and everything else sees interfaces. In large apps, Microsoft.Extensions.DependencyInjection automates the wiring, but its concepts are exactly these. Program.cs in the job runner is a composition root.
// Composition root: the only code that names concrete classes.
IStore store = new MemoryStore();
INotifier notifier = new ConsoleNotifier();
var service = new Service(store, notifier);
service.Save("a");
Console.WriteLine(store.Count);
interface IStore
{
int Count { get; }
void Add(string item);
}
interface INotifier
{
void Tell(string text);
}
class MemoryStore : IStore
{
private readonly List<string> items = new();
public int Count => items.Count;
public void Add(string item) => items.Add(item);
}
class ConsoleNotifier : INotifier
{
public void Tell(string text) => Console.WriteLine(text);
}
class Service(IStore store, INotifier notifier)
{
public void Save(string item)
{
store.Add(item);
notifier.Tell($"saved {item}");
}
}Check your prediction
saved a
1TimeProvider
The Intermediate course wrote a small IClock. .NET 8 added a standard one: TimeProvider. GetUtcNow reads the clock, and it also has timers. Library methods such as Task.Delay and CancellationTokenSource accept one, so a test can control time across a whole program. The package Microsoft.Extensions.TimeProvider.Testing supplies a FakeTimeProvider. A small subclass shows the idea.
TimeProvider real = TimeProvider.System;
Console.WriteLine(real.GetUtcNow().Year >= 2026);
var fake = new FixedTime(new DateTimeOffset(2026, 11, 2, 9, 0, 0, TimeSpan.Zero));
Console.WriteLine(Greeting(fake));
Console.WriteLine(Greeting(new FixedTime(new DateTimeOffset(2026, 11, 2, 15, 0, 0, TimeSpan.Zero))));
static string Greeting(TimeProvider time) => time.GetUtcNow().Hour < 12 ? "morning" : "afternoon";
class FixedTime(DateTimeOffset now) : TimeProvider
{
public override DateTimeOffset GetUtcNow() => now;
}Check your prediction
True
morning
afternoonThe job runner uses a narrower IDelayer, because that's all it needs, and it makes this course's tests easy to read. In a real service, passing TimeProvider to everything would be a reasonable choice.
Your turn
A rate limiter you can test
Write RateLimiter, built from an options record with Limit and Window (a TimeSpan) and a TimeProvider. TryAcquire() returns true if fewer than Limit calls have succeeded within the last Window. Bad options throw ArgumentOutOfRangeException from the constructor.
Write ManualTime, a TimeProvider with an Advance(TimeSpan) method. With a limit of 2 per 10 seconds, print the results of three calls in a row. Advance 5 seconds, and call again. Advance 5 more seconds, so the first two calls have expired, and call again. Show that a limit of 0 is refused.
When it works, it prints:
True
True
False
False
True
refusedvar now = TimeProvider.System.GetUtcNow();
Console.WriteLine(now.Year >= 2026);Hint 1: the idea
Keep the times of recent successes in a Queue. On each call, drop those that are too old from the front, then compare the count with the limit.
Hint 2: a first step
Write ManualTime first, as it's just a field and an override. A call exactly Window after an earlier one should count that earlier one as expired, so use <= when you drop items.
Show one solution
var time = new ManualTime(new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero));
var limiter = new RateLimiter(new LimiterOptions { Limit = 2, Window = TimeSpan.FromSeconds(10) }, time);
Console.WriteLine(limiter.TryAcquire());
Console.WriteLine(limiter.TryAcquire());
Console.WriteLine(limiter.TryAcquire());
time.Advance(TimeSpan.FromSeconds(5));
Console.WriteLine(limiter.TryAcquire());
time.Advance(TimeSpan.FromSeconds(5));
Console.WriteLine(limiter.TryAcquire());
try
{
new RateLimiter(new LimiterOptions { Limit = 0 }, time);
}
catch (ArgumentOutOfRangeException)
{
Console.WriteLine("refused");
}
record LimiterOptions
{
public int Limit { get; init; } = 10;
public TimeSpan Window { get; init; } = TimeSpan.FromSeconds(1);
}
class ManualTime(DateTimeOffset start) : TimeProvider
{
private DateTimeOffset now = start;
public override DateTimeOffset GetUtcNow() => now;
public void Advance(TimeSpan by)
{
now += by;
}
}
class RateLimiter
{
private readonly Queue<DateTimeOffset> recent = new();
private readonly LimiterOptions options;
private readonly TimeProvider time;
public RateLimiter(LimiterOptions options, TimeProvider time)
{
ArgumentOutOfRangeException.ThrowIfLessThan(options.Limit, 1);
ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(options.Window, TimeSpan.Zero);
this.options = options;
this.time = time;
}
public bool TryAcquire()
{
DateTimeOffset now = time.GetUtcNow();
while (recent.Count > 0 && recent.Peek() <= now - options.Window)
{
recent.Dequeue();
}
if (recent.Count >= options.Limit)
{
return false;
}
recent.Enqueue(now);
return true;
}
}True
True
False
False
True
refusedCompletion is saved in this browser only. It does not measure mastery.