Developer knowledge network · moderated exchange

UnreliableCode қауымдастығы

Әзірлеушілерді зерттеу, кері инженерия және кодтау қауымдастығы

Knowledge indexТірі
4Categories
919Threads
2.8KЖазбалар
Tutorial

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

roslyn_source_gen
Roslyn Compiler Dev
MEMBER
Өкіл: 120
Қосылу күні: Feb 2020
Хабарламалар: 12
Рахмет: 75
1 ай бұрын · 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
Өкіл: 138
Қосылу күні: Jul 2021
Хабарламалар: 10
Рахмет: 88
1 ай бұрын · 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
Өкіл: 103
Қосылу күні: Apr 2018
Хабарламалар: 40
Рахмет: 24
1 ай бұрын · Jul 8, 2026 8:56 PM
#3

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