← All blogs

FullStack Engineering CourseLesson 3 of 20 39 min

SOLID, Design Principles and Dependency Injection in .NET

What design principles are for

Code is changed far more often than it is written. Design principles keep that change cheap: when a requirement changes, the edit should go in one obvious place and break nothing else. SOLID is five principles for shaping classes and their dependencies. DRY, KISS and YAGNI stop you duplicating knowledge, adding needless complexity and building things nobody needs. Dependency injection is what makes most of these practical in .NET. The Gang of Four patterns that apply these principles (Strategy, Decorator, Factory and others) have their own course: Design Patterns in C#.

All examples in this lesson use one small domain: a service that receives healthcare claims, validates them, calculates fees and notifies the people involved.

S: the Single Responsibility Principle

A class should have one reason to change. "Reason to change" means one source of requirements (one group of people asking for changes), not one method. A class that validates claims, saves them and emails the provider changes when validation rules change (the business), when the database changes (the platform team) and when the email template changes (the communications team). When three groups edit one class, their unrelated changes break each other.

C#
// Three reasons to change in one class.
public class ClaimService
{
    public async Task SubmitAsync(Claim claim, CancellationToken ct)
    {
        if (claim.Amount <= 0) throw new ValidationException("Amount must be positive");
        if (claim.ServiceDate > DateTimeOffset.UtcNow) throw new ValidationException("Service date is in the future");

        using var connection = new SqlConnection("Server=...");             // persistence details
        await connection.ExecuteAsync("INSERT INTO Claims ...", claim);

        using var smtp = new SmtpClient("smtp.example.com");                 // notification details
        await smtp.SendMailAsync("claims@example.com", claim.ProviderEmail, "Received", "...");
    }
}

// One reason to change each; ClaimService now only coordinates the steps.
public sealed class ClaimService(IClaimValidator validator,
                                 IClaimRepository repository,
                                 IClaimNotifier notifier)
{
    public async Task SubmitAsync(Claim claim, CancellationToken ct)
    {
        validator.Validate(claim);                       // business rules
        await repository.AddAsync(claim, ct);            // storage
        await notifier.ClaimReceivedAsync(claim, ct);    // communication
    }
}

SRP is easy to overdo. Putting every method in its own class creates a maze of tiny types that is hard to follow. Split where requirements come from different places and change independently. Keep together the code that always changes together.

O: the Open/Closed Principle

Code should be open for extension but closed for modification: adding a new case should mean adding new code, not editing code that already works. The warning sign is a switch or if/else chain on a type that grows every time the business adds a variant, and that you have to find and edit in several places.

C#
// Every new payer type means editing this method (and retesting all the others).
public decimal CalculateFee(Claim claim) => claim.PayerType switch
{
    PayerType.Medicare   => claim.Amount * 0.02m,
    PayerType.Medicaid   => claim.Amount * 0.015m,
    PayerType.Commercial => Math.Max(5m, claim.Amount * 0.03m),
    _ => throw new NotSupportedException()
};

// Open for extension: each rule is its own class; a new payer is a new class plus one registration.
public interface IFeeRule
{
    bool AppliesTo(Claim claim);
    decimal Calculate(Claim claim);
}

public sealed class MedicareFeeRule : IFeeRule
{
    public bool AppliesTo(Claim claim) => claim.PayerType == PayerType.Medicare;
    public decimal Calculate(Claim claim) => claim.Amount * 0.02m;
}

public sealed class FeeCalculator(IEnumerable<IFeeRule> rules)   // the container injects every IFeeRule
{
    public decimal Calculate(Claim claim) =>
        (rules.FirstOrDefault(r => r.AppliesTo(claim))
            ?? throw new InvalidOperationException($"No fee rule for {claim.PayerType}"))
        .Calculate(claim);
}

// Registration: adding a payer never touches FeeCalculator.
builder.Services.AddSingleton<IFeeRule, MedicareFeeRule>();
builder.Services.AddSingleton<IFeeRule, MedicaidFeeRule>();
builder.Services.AddSingleton<IFeeRule, CommercialFeeRule>();
builder.Services.AddSingleton<FeeCalculator>();

This is the Strategy pattern, wired up by the DI container. The real question is when to use it. A switch over three stable cases in one place is perfectly readable. Turn it into classes when the cases keep growing, contain their own logic, or the same switch appears in several places. Apply Open/Closed in response to change you have actually seen, not by adding extension points everywhere in advance.

There are two basic ways to make code open for extension:

  • Inheritance: a base class declares virtual or abstract methods, and a new subclass overrides them. This is the original form of the principle. It works, but a subclass depends on its parent's internals (a change in the base class can break every subclass), and C# allows only one base class.
  • Composition: the class depends on an interface and receives an implementation. A new behaviour is a new class that implements the interface. The pieces stay independent, and you can combine several. This is why the usual advice is to prefer composition over inheritance.
C#
// Inheritance: extend by subclassing.
public abstract class FeeRuleBase
{
    public decimal Calculate(Claim claim) => Math.Round(CalculateRaw(claim), 2);  // fixed part
    protected abstract decimal CalculateRaw(Claim claim);                       // varying part
}
public sealed class MedicaidFee : FeeRuleBase
{
    protected override decimal CalculateRaw(Claim claim) => claim.Amount * 0.015m;
}

// Composition: extend by plugging in a different object.
public sealed class FeeCalculator(IFeeRule rule)
{
    public decimal Calculate(Claim claim) => Math.Round(rule.Calculate(claim), 2);
}

Common techniques built on these two:

  • Strategy: swap one algorithm for another behind an interface (the fee rules above).
  • Template Method: a base class fixes the steps, and subclasses fill in the varying ones (FeeRuleBase above).
  • Decorator: wrap an object to add behaviour (caching, logging, retries) without changing it.
  • Pipelines and Chain of Responsibility: add a step to a chain, as ASP.NET Core middleware and MediatR behaviours do.
  • Events and Observer: add a new subscriber without touching the publisher.
  • Delegates: accept a Func or Action, so the caller supplies the varying part.
  • Plugins and DI registration: register one more implementation, and code that takes IEnumerable<T> picks it up.
  • Data-driven rules: keep values or rules in configuration or a database, so a change needs no code change at all.

Are extension methods OCP? Partly. They let you add new operations to a type without modifying it, even a type you do not own. LINQ adds Where and Select to every IEnumerable<T> this way, and AddDbContext is an extension method on IServiceCollection. In that sense the type is closed for modification but open for new operations. But extension methods cannot change existing behaviour, cannot read private state, and are chosen at compile time from the variable's declared type, not from the object's real type at runtime. So they cannot provide the varying behaviour that OCP is mostly about. Use them to add convenient operations; use composition or inheritance when the behaviour itself must vary.

C#
public static class ClaimExtensions
{
    // Adds an operation to Claim without changing the Claim class.
    public static bool IsHighValue(this Claim claim) => claim.Amount > 10_000m;
}

if (claim.IsHighValue()) RequireManualReview(claim);

L: the Liskov Substitution Principle

Code that uses a base type or interface must work correctly with every implementation of it. In practice, an implementation must not:

  • require more from callers than the contract does
  • deliver less than the contract promises
  • throw exceptions the contract does not mention

You can spot violations when callers check the concrete type, or when an implementation throws NotSupportedException.

C#
public interface IClaimStore
{
    Task AddAsync(Claim claim, CancellationToken ct);
    Task<Claim?> GetAsync(int id, CancellationToken ct);
}

// Violates LSP: code written against IClaimStore will fail at runtime with this one.
public sealed class ArchiveClaimStore(IColdStorage storage) : IClaimStore
{
    public Task AddAsync(Claim claim, CancellationToken ct) =>
        throw new NotSupportedException("The archive is read-only");
    public Task<Claim?> GetAsync(int id, CancellationToken ct) => storage.FindClaimAsync(id, ct);
}

// Fix: model what each implementation really supports (this is also the Interface Segregation Principle).
public interface IClaimReader { Task<Claim?> GetAsync(int id, CancellationToken ct); }
public interface IClaimWriter { Task AddAsync(Claim claim, CancellationToken ct); }

public sealed class ArchiveClaimReader(IColdStorage storage) : IClaimReader    // only what it can honour
{
    public Task<Claim?> GetAsync(int id, CancellationToken ct) => storage.FindClaimAsync(id, ct);
}

public sealed class SqlClaimStore(ClaimsDbContext db) : IClaimReader, IClaimWriter
{
    public async Task AddAsync(Claim claim, CancellationToken ct)
    {
        db.Claims.Add(claim);
        await db.SaveChangesAsync(ct);
    }
    public Task<Claim?> GetAsync(int id, CancellationToken ct) => db.Claims.FindAsync([id], ct).AsTask();
}

The .NET library has a well-known violation itself: ReadOnlyCollection<T> implements IList<T>, but its Add method throws NotSupportedException. That is why IReadOnlyList<T> and IReadOnlyCollection<T> were added later. Subtler violations do just as much damage: an implementation that ignores the CancellationToken, returns null where others return an empty list, or caches results when callers expect fresh data. When you write a second implementation of an interface, run the same tests against both. These contract tests are the practical way to check that implementations can replace each other.

I: the Interface Segregation Principle

Clients should not depend on methods they do not use. A large interface ties every consumer to every member, which causes three problems:

  • A change to one method can break all consumers.
  • Test fakes must implement members the test never calls.
  • Implementations end up throwing NotSupportedException (the Liskov problem above).

Split interfaces by what each client needs.

C#
// One fat interface: the reporting job depends on Delete, the API on bulk export.
public interface IClaimRepository
{
    Task<Claim?> GetAsync(int id, CancellationToken ct);
    Task<IReadOnlyList<Claim>> SearchAsync(ClaimQuery query, CancellationToken ct);
    Task AddAsync(Claim claim, CancellationToken ct);
    Task UpdateStatusAsync(int id, ClaimStatus status, CancellationToken ct);
    Task DeleteAsync(int id, CancellationToken ct);
    IAsyncEnumerable<Claim> ExportAllAsync(DateOnly from, DateOnly to, CancellationToken ct);
}

// Role interfaces: each client asks only for what it uses. One class can still implement all of them.
public interface IClaimQueries { Task<Claim?> GetAsync(int id, CancellationToken ct);
                                 Task<IReadOnlyList<Claim>> SearchAsync(ClaimQuery query, CancellationToken ct); }
public interface IClaimCommands { Task AddAsync(Claim claim, CancellationToken ct);
                                  Task UpdateStatusAsync(int id, ClaimStatus status, CancellationToken ct); }
public interface IClaimExport { IAsyncEnumerable<Claim> ExportAllAsync(DateOnly from, DateOnly to, CancellationToken ct); }

// Register one implementation behind all three role interfaces, sharing one instance per scope.
builder.Services.AddScoped<SqlClaimRepository>();
builder.Services.AddScoped<IClaimQueries>(sp => sp.GetRequiredService<SqlClaimRepository>());
builder.Services.AddScoped<IClaimCommands>(sp => sp.GetRequiredService<SqlClaimRepository>());
builder.Services.AddScoped<IClaimExport>(sp => sp.GetRequiredService<SqlClaimRepository>());

Splitting reads from writes like this is a first small step toward CQRS (Command Query Responsibility Segregation), which a later lesson covers in full.

D: the Dependency Inversion Principle

High-level business logic should not depend on low-level details. Both should depend on abstractions, and the abstraction belongs to the business logic. ClaimService decides what happens when a claim is submitted. SQL Server, SMTP and the system clock are details. If ClaimService creates a SqlConnection itself, you cannot test it without a database or move it to another store without rewriting it. If it depends on an IClaimCommands interface that it owns, the SQL class depends on ClaimService's interface instead of the other way round. The dependency has been inverted.

Time is an easy dependency to miss. Code that calls DateTime.UtcNow directly cannot be tested for "what happens after 30 days" without waiting 30 days. .NET 8 added TimeProvider for exactly this:

C#
public sealed class ClaimDeadlineChecker(TimeProvider clock)
{
    // Claims must be filed within 90 days of the service date.
    public bool IsLate(Claim claim) =>
        clock.GetUtcNow() > claim.ServiceDate.AddDays(90);
}

// Production: the real clock.
builder.Services.AddSingleton(TimeProvider.System);

// Test (package Microsoft.Extensions.TimeProvider.Testing): time under your control.
var clock = new FakeTimeProvider(new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero));
var checker = new ClaimDeadlineChecker(clock);
var claim = new Claim { ServiceDate = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero) };

Console.WriteLine(checker.IsLate(claim));   // day 0
clock.Advance(TimeSpan.FromDays(91));
Console.WriteLine(checker.IsLate(claim));   // day 91
Output
False
True

Dependency inversion is the principle. Dependency injection is a technique for applying it (passing dependencies in instead of creating them). A DI container is a tool that does the wiring for you. Clean and hexagonal architecture, covered in a later lesson, apply the same idea to whole projects: the domain defines ports (interfaces), and the infrastructure provides adapters (implementations).

Inversion of Control (IoC)

Inversion of Control is a broader idea than dependency inversion. In normal code, your code calls the libraries it needs and controls the flow. With IoC, the control is inverted: a framework or container controls the flow and calls your code when needed. This is often called the Hollywood principle: "don't call us, we'll call you". ASP.NET Core is full of it: you never call your controller or middleware yourself; the framework creates them and calls them for each request.

The three terms are related but different:

  • Dependency Inversion Principle (DIP): business logic depends on abstractions it owns, not on details. It is about the direction of dependencies.
  • Inversion of Control (IoC): something outside your code controls the flow and calls your code. It is about who is in control.
  • Dependency Injection (DI): one way to achieve IoC. A container creates objects and passes in their dependencies, so a class does not create or look up what it needs.

DI is the most common form of IoC, but not the only one. Other ways to invert control:

  • Pure DI: pass dependencies in by hand in one place (the composition root, usually Program.cs), without a container.
  • Factory: depend on a factory interface, such as IPayerClientFactory.Create(payerCode), when the choice depends on runtime data.
  • Delegates and callbacks: ask for a function, such as Func<DateTimeOffset> for the current time, and the caller decides what runs.
  • Events: raise an event such as ClaimSubmitted and let email, audit and billing subscribe. The subscribers are called; the publisher does not know them.
  • Template Method: a base class controls the steps and calls abstract methods that subclasses fill in.
  • Frameworks and hosts: middleware, controllers, BackgroundService and filters are all called by ASP.NET Core, not by you.
  • Messaging: send a command or event through a mediator or message bus; the handler is found and called for you.
  • Plugins: the host loads implementations from separate assemblies at runtime and calls them through interfaces.
  • Service locator: a class asks a registry for its dependencies. It inverts control too, but it hides what a class needs and moves errors to runtime, so avoid it.

DRY, KISS and YAGNI

DRY (Don't Repeat Yourself) is about knowledge, not text. Each business rule should live in one place, so changing the rule means changing one place. Code that looks the same but represents different rules is not duplication. A 90-day claim filing limit and a 90-day password expiry share a number, but merging them into one constant ties together two things that change for different reasons. Forcing look-alike code into one shared abstraction produces the wrong abstraction, which then grows flags and parameters to handle callers it was not designed for. A practical guide is the rule of three: accept a second copy, and extract the shared idea when a third appears and you can see what really varies.

C#
// Duplicated knowledge: the same rule written twice will drift apart.
if (claim.Amount > 10_000m) RequireManualReview(claim);       // in the API
if (claim.Amount > 10_000m) flags.Add("HighValue");           // in the batch importer

// One home for the rule.
public static class ClaimRules
{
    public const decimal ManualReviewThreshold = 10_000m;
    public static bool NeedsManualReview(Claim claim) => claim.Amount > ManualReviewThreshold;
}

KISS (Keep It Simple) means choosing the simplest design that meets today's needs: a plain method over a clever generic framework, a switch over a plugin system for three cases, one service over microservices for a small team. Simple code is easier to read, test, debug and change. Complexity should have to earn its place. YAGNI (You Aren't Gonna Need It) applies KISS to the future: do not build features, settings or extension points that nobody has requested. That work costs effort now, adds code everyone must understand, and usually guesses the future wrong.

Applied mechanically, these principles conflict with SOLID. An interface for every class, a strategy for every if statement and a layer for every concern turns SOLID into ceremony and breaks KISS and YAGNI. The balance: keep code simple until a real change shows where flexibility is needed, then refactor toward the principle suggested by that change. Good tests make that later refactoring safe.

PrincipleAsk yourselfOverdone, it becomes
Single ResponsibilityWho would ask for this class to change?Dozens of one-method classes
Open/ClosedDoes a new variant mean editing working code?Extension points nobody uses
Liskov SubstitutionDoes every implementation honour the whole contract?(rarely overdone)
Interface SegregationDoes each client use everything it depends on?One-method interfaces everywhere
Dependency InversionDoes business logic depend on details such as the database, email or clock?An interface for every class
DRYIs this the same knowledge, or just similar text?The wrong abstraction, with flags
KISSIs there a simpler design that works today?(rarely overdone)
YAGNIHas anyone actually asked for this?(rarely overdone)

Two related guidelines:

  • Prefer composition over inheritance. Inheriting to reuse code ties a class to its parent's internals, while holding another object and calling it (as the decorators and strategies above do) keeps the pieces independent.
  • Follow the Law of Demeter (talk only to your immediate neighbours). claim.Provider.Address.City.Name reaches through four objects and ties the caller to all their shapes. Ask the object that owns the information instead.

Dependency injection in ASP.NET Core

ASP.NET Core has a built-in DI container. You register services in Program.cs with a lifetime. The container creates them, passes their dependencies into their constructors and disposes them at the end of their lifetime. Constructor injection is the default: a class lists what it needs as constructor parameters (or primary constructor parameters, as in the examples above). This makes its dependencies visible and lets tests pass in fakes directly.

LifetimeOne instance perUse it forWatch out for
TransientEvery resolutionLightweight, stateless servicesDisposable transients resolved from the root provider are kept until the app shuts down
ScopedScope (one HTTP request in ASP.NET Core)DbContext, unit of work, per-request stateNot available outside a scope: background services must create one
SingletonThe whole applicationCaches, configuration, HttpClient handlers, stateless services shared by allMust be thread-safe; must not hold Scoped services

The rule that ties lifetimes together: a service may only depend on services that live at least as long as it does. A Singleton that receives a Scoped DbContext keeps that one DbContext forever, shared by every request on every thread. This is called a captive dependency. ASP.NET Core checks for it at startup in the Development environment (ValidateScopes and ValidateOnBuild) and throws an error, so turn the same checks on in tests or in every environment. Code that runs outside a request, such as a BackgroundService, creates its own scope for each unit of work:

C#
var builder = WebApplication.CreateBuilder(args);

// Catch lifetime mistakes and missing registrations at startup in every environment.
builder.Host.UseDefaultServiceProvider(o => { o.ValidateScopes = true; o.ValidateOnBuild = true; });

builder.Services.AddDbContext<ClaimsDbContext>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("Claims")));
builder.Services.AddScoped<IClaimCommands, SqlClaimRepository>();
builder.Services.AddHostedService<OverdueClaimsWorker>();

public sealed class OverdueClaimsWorker(IServiceScopeFactory scopes, TimeProvider clock) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        using var timer = new PeriodicTimer(TimeSpan.FromHours(1), clock);
        while (await timer.WaitForNextTickAsync(stoppingToken))
        {
            await using var scope = scopes.CreateAsyncScope();             // a fresh scope per run
            var db = scope.ServiceProvider.GetRequiredService<ClaimsDbContext>();
            var now = clock.GetUtcNow();
            await db.Claims.Where(c => c.Status == ClaimStatus.Pending && c.DueDate < now)
                           .ExecuteUpdateAsync(s => s.SetProperty(c => c.Status, ClaimStatus.Overdue), stoppingToken);
        }   // scope disposed here: the DbContext goes with it
    }
}

Registration techniques

You can register several implementations of one interface. Injecting IEnumerable<T> gives you all of them in registration order (like FeeCalculator above), and injecting T gives you the last one registered. Library code should use TryAdd so it never overrides a registration made by the application. When a consumer needs one specific implementation by name, .NET 8 keyed services save you writing a factory:

C#
builder.Services.AddKeyedSingleton<IClaimNotifier, EmailNotifier>("email");
builder.Services.AddKeyedSingleton<IClaimNotifier, SmsNotifier>("sms");

public sealed class UrgentClaimHandler([FromKeyedServices("sms")] IClaimNotifier notifier)
{
    public Task HandleAsync(Claim claim, CancellationToken ct) => notifier.ClaimReceivedAsync(claim, ct);
}

// In a library: only register if the application has not registered its own.
services.TryAddSingleton(TimeProvider.System);

The built-in container does not support decorators directly, but a factory registration does the job: register the inner class as itself, and register the interface as the decorator that wraps it. (The Scrutor package adds a Decorate method that does this in one line.)

C#
builder.Services.AddMemoryCache();
builder.Services.AddHttpClient<PayerApiClient>(c => c.BaseAddress = new Uri("https://payer.example.com"));

// IPayerClient resolves to the caching decorator, which wraps the real HTTP client.
builder.Services.AddScoped<IPayerClient>(sp =>
    new CachedPayerClient(sp.GetRequiredService<PayerApiClient>(),
                          sp.GetRequiredService<IMemoryCache>()));

public sealed class CachedPayerClient(IPayerClient inner, IMemoryCache cache) : IPayerClient
{
    public async Task<Payer> GetPayerAsync(string code, CancellationToken ct) =>
        (await cache.GetOrCreateAsync($"payer:{code}", entry =>
        {
            entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10);
            return inner.GetPayerAsync(code, ct);
        }))!;
}

The options pattern

Configuration (appsettings.json, environment variables, Key Vault) should reach services through typed options classes, not raw IConfiguration lookups. Bind a section to a class, validate it, and fail at startup instead of on the first request that needs a missing value:

C#
public sealed class PayerApiOptions
{
    public const string Section = "PayerApi";
    [Required, Url] public string BaseUrl { get; init; } = "";
    [Range(1, 100)] public int MaxConcurrentCalls { get; init; } = 8;
    public TimeSpan Timeout { get; init; } = TimeSpan.FromSeconds(10);
}

builder.Services.AddOptions<PayerApiOptions>()
    .BindConfiguration(PayerApiOptions.Section)
    .ValidateDataAnnotations()
    .ValidateOnStart();                 // a bad config stops the app at startup, not at 2 a.m.

public sealed class PayerApiClient(HttpClient http, IOptions<PayerApiOptions> options) { /* options.Value.BaseUrl */ }
InterfaceLifetimeSees configuration changesUse it in
IOptions<T>SingletonNo: read onceMost services; settings that don't change at runtime
IOptionsSnapshot<T>ScopedYes, per requestScoped services that should see reloaded settings
IOptionsMonitor<T>SingletonYes, with OnChange callbacksSingletons and background services that react to changes

DI smells

Some patterns show that DI is being misused:

  • Service locator (injecting IServiceProvider and calling GetService in business code) hides a class's real dependencies and moves wiring errors from startup to runtime. Keep it to setup code such as factories and background workers.
  • A constructor with eight or more parameters is not a DI problem but an SRP one: the class does too much and should be split.
  • Calling new on a service that has its own dependencies bypasses the container and its lifetimes.
  • Registering everything as Singleton to avoid lifetime errors makes services share state across requests and threads.
  • Static helper classes that read HttpContext or configuration directly cannot be tested or replaced.

Check your understanding

QuestionShort answer
What does "one reason to change" mean in SRP?One actor or source of requirements, not one method. Split where changes come from independently.
How do you apply Open/Closed without overengineering?Wait for real variation (a growing switch, the same switch in several places), then move each case into its own class, for example a strategy registered in DI.
Inheritance or composition for Open/Closed?Both work. Composition (an interface plus pluggable implementations) is usually preferred, because subclasses depend on their parent's internals.
Are extension methods OCP?Partly: they add operations to a type without modifying it, but they cannot change or vary behaviour at runtime.
Give an LSP violation.An implementation that throws NotSupportedException for a member of its interface, such as ReadOnlyCollection<T>.Add from IList<T>.
How do ISP and LSP relate?Fat interfaces force implementations to stub members they cannot support, which breaks substitutability. Role interfaces fix both.
Dependency inversion vs dependency injection?Dependency inversion is a design rule: business logic should depend on an interface it defines (IClaimWriter), not on a concrete class (SqlClaimRepository). Dependency injection is a technique: a class receives its dependencies, usually through its constructor, instead of creating them with new. A DI container is a tool that creates the objects and passes them in for you.
What is Inversion of Control?A framework or container controls the flow and calls your code ("don't call us, we'll call you"). DI is one form of IoC; events, callbacks, Template Method and frameworks are others.
Is all duplication a DRY violation?No. DRY is about duplicated knowledge. Similar-looking code that represents different rules should stay separate.
What is a captive dependency?A longer-lived service holding a shorter-lived one, such as a Singleton holding a Scoped DbContext. Detected by ValidateScopes.
How does a BackgroundService use a DbContext?Inject IServiceScopeFactory and create a scope per unit of work, or use IDbContextFactory.
IOptions, IOptionsSnapshot or IOptionsMonitor?IOptions for static settings; Snapshot per request in scoped services; Monitor in singletons that react to changes.
How do you decorate a service with the built-in container?Register the inner type as itself and the interface with a factory that wraps it (or use Scrutor's Decorate).
How do you make time testable?Depend on TimeProvider; use FakeTimeProvider in tests and Advance it.

Summary

  • Give each class one source of change, and add new variants as new classes rather than edits.
  • Make every implementation honour its whole contract, and shape interfaces around their clients.
  • Make business logic depend on abstractions it owns, not on infrastructure.
  • Keep each piece of knowledge in one place, but do not merge code that only looks alike.
  • Choose the simplest design that works, build only what has been requested, and refactor toward a principle when a real change shows the need.
  • In ASP.NET Core, use constructor injection with the right lifetime, and never let a longer-lived service hold a shorter-lived one.
  • Validate scopes and options at startup, and create scopes in background work.
  • Use keyed services, factory registrations and the options pattern instead of a service locator.

The next lesson uses all of this to design web APIs in ASP.NET Core: REST resources and status codes, versioning, Problem Details, OpenAPI-first design, pagination, rate limiting, gRPC and webhooks.

Found this useful? Share it: LinkedIn X

Comments