Developer knowledge network ยท moderated exchange

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Knowledge indexLive
4Categories
919Threads
2.8KPosts
Tutorial

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

roslyn_source_gen
Roslyn Compiler Dev
MEMBER
Rep: 120
Join Date: Feb 2020
Posts: 12
Thanks: 75
1 months ago ยท 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
Rep: 138
Join Date: Jul 2021
Posts: 10
Thanks: 88
1 months ago ยท 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
Rep: 103
Join Date: Apr 2018
Posts: 40
Thanks: 24
1 months ago ยท Jul 8, 2026 8:56 PM
#3

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