Developer knowledge network · moderated exchange

UnreliableCode-Community

Community für Entwicklerforschung, Reverse Engineering und Codierung

Knowledge indexLive
4Categories
919Threads
2.8KBeiträge
Tutorial

C# 12 Primary Constructors on Classes and Structs: Clean Dependency Injection [StackOverflow Architecture Guide]

roslyn_source_gen
Roslyn Compiler Dev
MEMBER
Vertreter: 120
Beitrittsdatum: Feb 2020
Beiträge: 12
Danke: 75
Vor 1 Monaten · Jul 8, 2026 1:51 AM
#1

Simplifying boilerplate dependency injection with C# 12 Primary Constructors:

CSHARP
// C# 12 Primary Constructor syntax
public class PaymentProcessor(ILogger<PaymentProcessor> logger, IPaymentGateway gateway, IOrderRepository repo)
{
    public async Task ProcessAsync(OrderId id)
    {
        logger.LogInformation("Processing order {Id}", id);
        await gateway.ChargeAsync(id);
        await repo.MarkAsPaidAsync(id);
    }
}

Eliminates private field declarations (private readonly ILogger _logger;) and constructor assignment boilerplate, making service classes concise and readable!

generic_math_geek
C# 11 Math Guru
MEMBER
Vertreter: 138
Beitrittsdatum: Jul 2021
Beiträge: 10
Danke: 88
Vor 1 Monaten · Jul 8, 2026 4:34 AM
#2

Primary constructors make ASP.NET Core service and controller definitions 50% shorter.

dotnet_runtime_architect
.NET Core Specialist
MEMBER
Vertreter: 103
Beitrittsdatum: Apr 2018
Beiträge: 40
Danke: 24
Vor 1 Monaten · Jul 8, 2026 8:56 PM
#3

Works on records, classes, and struct types across the board.