Developer knowledge network · moderated exchange

Сообщество UnreliableCode

Сообщество разработчиков, обратного проектирования и кодирования

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.