C# / .NET Compendium PLEN
.NET / C# / SOLID, Clean Code, DI

Ways to implement DI (Dependency Injection)

In an interview this question usually checks whether you know not only "constructor DI" but also the other variants and when to use each - it's a common follow-up after the DI topic.

1. Constructor Injection - the default choice (99% of cases)

Dependencies are passed through the constructor and assigned to readonly fields.

public class OrderService : IOrderService
{
    private readonly IOrderRepository _repository;
    private readonly ILogger<OrderService> _logger;

    public OrderService(IOrderRepository repository, ILogger<OrderService> logger)
    {
        _repository = repository ?? throw new ArgumentNullException(nameof(repository));
        _logger = logger;
    }
}

Advantages: - Immutability - readonly, the dependency cannot change after the object is created - Fail-fast - the object cannot even be created without the required dependencies (the error is detected immediately at startup, not while running) - Explicitness - looking at the constructor you see ALL of the class's dependencies at once - DI containers (Microsoft.Extensions.DependencyInjection, Autofac) use this as the default mechanism

Disadvantage: with many dependencies the constructor grows (see "constructor bloat" below).

2. Property Injection (Setter Injection)

The dependency is set through a public property, not through the constructor.

public class ReportGenerator
{
    // Optional dependency - if not set, the class still works (with default behaviour)
    public ILogger Logger { get; set; } = NullLogger.Instance;

    public void Generate(Report report)
    {
        Logger.Log("Generowanie raportu...");
        // ...
    }
}
var generator = new ReportGenerator();
generator.Logger = new FileLogger(); // opcjonalne nadpisanie

When to use: - The dependency is optional (the class works sensibly without it, with a default value) - A framework forces a parameterless constructor (e.g. some older serialization frameworks, WPF controls created by the XAML parser)

Disadvantage: the object can exist in an incomplete, "half-way" state - nothing guarantees that someone will set the property before the class is used. No fail-fast.

3. Method Injection (Parameter Injection)

The dependency is passed as a parameter of a specific method and is not stored in a class field.

public class OrderProcessor
{
    // Not every method in the class needs this dependency -
    // only this one, so there's no point holding it as a field
    public void ProcessOrder(Order order, IDiscountCalculator discountCalculator)
    {
        var discount = discountCalculator.Calculate(order);
        order.TotalAmount -= discount;
    }
}

When to use: - The dependency is needed in only one method, not in the whole class - The dependency changes on every call (e.g. different strategies passed each time) - A classic example: IComparer<T> passed to List<T>.Sort(IComparer<T> comparer)

4. Ambient Context (rarer, controversial)

A dependency available globally, without being passed explicitly - e.g. through a static property or AsyncLocal.

public static class CurrentUser
{
    private static readonly AsyncLocal<string> _userId = new();
    public static string UserId
    {
        get => _userId.Value;
        set => _userId.Value = value;
    }
}

// Use anywhere, without passing it through the constructor
public class AuditLogger
{
    public void Log(string action)
    {
        Console.WriteLine($"{CurrentUser.UserId}: {action}");
    }
}

Rarely recommended - it hides the class's real dependencies (you can't see them in the constructor), makes testing harder (global state shared between tests) and thread-safety requires care. A real example built into .NET: Thread.CurrentPrincipal, HttpContext.Current (old ASP.NET).

5. Service Locator - an anti-pattern, but worth knowing

Instead of injecting concrete dependencies, the class gets access to a "service locator" and fetches what it needs from it on its own.

// ❌ Anty-pattern
public class OrderService
{
    public void ProcessOrder(Order order)
    {
        var repository = ServiceLocator.Current.GetInstance<IOrderRepository>();
        var logger = ServiceLocator.Current.GetInstance<ILogger>();
        // ...
    }
}

Why it's an anti-pattern (a common interview question: "why is Service Locator bad"): - Hidden dependencies - looking at the constructor/signature of the class, you can't see what it actually needs - you only find out by reading the whole implementation - The class now depends on the DI container itself, not on an abstraction - this inverts the meaning of the Dependency Inversion Principle - Missing-registration errors show up at runtime, on a specific call of GetInstance<T>(), instead of at application startup (fail-fast) as with constructor injection - Harder testing - you have to mock the whole ServiceLocator instead of a single dependency

This is, by the way, the difference compared with IServiceScopeFactory, which we discussed with Singletons - CreateScope() + GetRequiredService<T>() looks similar to a Service Locator, but the difference is significant: you do it deliberately, in one specific place, to solve a lifetime problem (Scoped in a Singleton), not as a general way of delivering all dependencies across the entire application.

Comparison in a table

Approach When to use Fail-fast? Visibility of dependencies
Constructor Injection The default choice, required dependencies ✅ Yes ✅ Full, in the signature
Property Injection An optional dependency ❌ No ⚠️ Partial
Method Injection A dependency used in only one method ✅ Yes (at the method level) ✅ In the method signature
Ambient Context Rarely - cross-cutting data (e.g. user context) ❌ No ❌ Hidden
Service Locator Avoid ❌ No (only at runtime) ❌ Completely hidden

A question they may ask as a follow-up

"What do you do when a constructor has 8 dependencies?" - this is so-called constructor bloat/over-injection, and a good answer is not "I just leave it like that", but recognising that it is a sign of breaking the Single Responsibility Principle (back to SOLID) - the class probably does too many different things and is worth splitting into smaller, more specialised classes, each with 2-3 dependencies.


The constructor is what you will almost always use in practice - but the interviewer may want to hear that you understand the trade-offs of the other approaches, not just that you know one name.

Buy me a coffee