📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What are constructor injection, property injection and method injection? Why does the built-in .NET container only support constructor injection, and where do you still see method injection in ASP.NET Core?

Compares constructor, property and method injection, explains why Microsoft.Extensions.DependencyInjection supports only constructors, and shows where ASP.NET Core injects into methods and properties (endpoint parameters, [FromServices], InvokeAsync, @inject, [Inject]).

Junior Theory Beginner aspnet-core constructor-injection dependency-injection method-injection property-injection

🎯 Key points

  • Constructor injection: required dependencies, object valid after construction, immutable fields
  • Property injection: optional dependencies set after construction; risk of half-initialised objects
  • Method injection: dependency passed to the one method that needs it
  • Built-in container does constructor injection only, by design (explicit, simple, fast)
  • ASP.NET Core injects into Minimal API handler parameters and MVC actions with [FromServices]
  • Convention-based middleware gets scoped services through InvokeAsync parameters
  • Razor @inject and Blazor [Inject] are framework-level property injection
  • Optional dependencies: use a null object or default implementation rather than a settable property

⏱ 30-second answer

  • Constructor injection passes required dependencies to the constructor, so the object is complete and valid the moment it exists and fields can be readonly.
  • Property injection sets dependencies through settable properties after construction; it suits truly optional dependencies but allows half-initialised objects.
  • Method injection passes a dependency only to the method that needs it.

The built-in container supports constructor injection only, by design: it keeps dependencies explicit and resolution simple. ASP.NET Core adds method-level injection on top: Minimal API handler parameters, [FromServices] on MVC actions, and middleware InvokeAsync parameters. Razor's @inject and Blazor's [Inject] are framework-level property injection.

The trade-off: constructors make dependencies obvious, but a long constructor is a design smell you can't hide.

🗣 Full answer (senior)

How I would answer this in an interview

"Constructor injection is the default and the one I reach for. The class lists what it needs as constructor parameters, the container supplies them, and once the constructor returns the object is fully usable. Fields can be readonly, there's no 'did someone set this yet' check, and the constructor documents the dependencies. Property injection means the container sets public properties after construction. It's meant for optional dependencies, but in practice it hides requirements and lets you get a half-built object. Method injection is passing the dependency into the specific method that uses it, which is great when only one operation needs it or when it varies per call.

Microsoft's container only does constructor injection on purpose. It's meant to be the minimal common denominator that libraries can rely on, and constructors are explicit and fast to resolve. But ASP.NET Core itself does method injection in a few places: Minimal API handlers get services as parameters, MVC actions can take [FromServices] parameters, and convention-based middleware is constructed once as a singleton, so scoped services go into InvokeAsync as parameters instead of the constructor. Razor views use @inject, and Blazor components use [Inject], which are property injection done by the framework, not the container.

The mistake I see is people wanting property injection because a constructor has twelve parameters. That's the constructor telling you the class does too much. I'd rather split the class or introduce a facade than hide the dependencies."


The three forms

Form How Good for Downsides
Constructor Parameters on the constructor Required dependencies (almost all) Long constructors expose design smells (a feature)
Property Settable public property Truly optional dependencies, framework components Half-initialised objects, hidden requirements, mutability
Method Parameter on the method One operation needs it, or it varies per call Callers must supply it every time

Where ASP.NET Core injects outside constructors

Place Mechanism Why it exists
Minimal API handler Service parameters inferred via IServiceProviderIsService Handlers are delegates, not classes
MVC action [FromServices] parameter Avoid constructor bloat for one action's dependency
Convention-based middleware InvokeAsync(HttpContext, IScopedService) Middleware instance is a singleton; scoped services must come per request
Razor view @inject IFoo Foo Views are generated classes
Blazor component [Inject] property Components are created by the renderer

Production example

A convention-based middleware took a scoped TenantContext-style service in its constructor. Because middleware is created once, the first request's instance was captured and reused for every request, leaking one request's data into others in testing. Moving the dependency to an InvokeAsync parameter fixed it, and turning on ValidateScopes would have thrown at start-up.

🔍 What the interviewer is checking

Checks the candidate knows the three injection styles, why constructor injection is preferred, and the framework places where other styles appear.

Green flags

  • Explains constructor injection as making objects valid at construction
  • Knows the built-in container has no property injection
  • Mentions the middleware InvokeAsync rule for scoped services
  • Treats long constructors as a design signal

Red flags

  • Prefers property injection for convenience
  • Puts scoped services in middleware constructors
  • Doesn't know Minimal API handlers can receive services

📚 Learn in depth

1. Why constructor injection is the default

A constructor is the one place where an object can enforce its invariants before anyone can use it:

public sealed class InvoiceService(IInvoiceRepository repo, TimeProvider clock)
{
    // repo and clock are always set; no null checks in methods
}

It also makes the dependency graph visible to the container, so it can validate it (ValidateOnBuild) and detect cycles.

2. Property injection and temporal coupling

new InvoiceService()          ← object exists but is unusable
  .Logger = ...               ← forgotten in one code path?
  .Repository = ...
service.Create()              ← NullReferenceException at run time

That ordering dependency is called temporal coupling. The built-in container won't do this at all; Autofac can (PropertiesAutowired()).

3. Method injection in the framework

ASP.NET Core decides how to bind each handler parameter. For Minimal APIs it asks IServiceProviderIsService whether the type is a registered service; if yes, it resolves it from HttpContext.RequestServices (the request scope).

Request → endpoint delegate (int id, IOrderService orders, CancellationToken ct)
             │ route      │ RequestServices      │ RequestAborted

For convention-based middleware, the constructor runs once at pipeline build time; InvokeAsync parameters after HttpContext are resolved from the request scope on every call. IMiddleware implementations are instead resolved from the container per request, so they can take scoped services in the constructor (register them as scoped or transient).

4. Optional dependencies without property injection

Use a null object (NullLogger<T>.Instance), a default registration with TryAdd, or a constructor parameter with a default value. All keep the object valid at construction.

Try it yourself

  1. Write middleware with a scoped service in its constructor, enable ValidateScopes, and read the exception. Move the service to InvokeAsync.
  2. Create a Minimal API handler with a service parameter and one without registration; see which is bound from the body.
  3. Add a settable ILogger property to a class and resolve it from the built-in container; observe it stays null.
  4. Convert a 6-parameter constructor into two smaller classes and compare the tests.

💻 Code

Constructor injection for the class, method injection where the framework supports it.

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<IRequestAudit, RequestAudit>();
builder.Services.AddScoped<IOrderService, OrderService>();

var app = builder.Build();
app.UseMiddleware<AuditMiddleware>();

// Method injection: Minimal API handler parameters come from the request scope.
app.MapGet("/orders/{id:int}", async (int id, IOrderService orders, CancellationToken ct) =>
    await orders.FindAsync(id, ct) is { } order ? Results.Ok(order) : Results.NotFound());

app.Run();

public interface IOrderService { Task<string?> FindAsync(int id, CancellationToken ct); }

// Constructor injection: required dependencies, object valid after construction.
public sealed class OrderService(TimeProvider clock) : IOrderService
{
    public Task<string?> FindAsync(int id, CancellationToken ct) =>
        Task.FromResult<string?>($"order {id} at {clock.GetUtcNow():O}");
}

public interface IRequestAudit { void Record(string path); }
public sealed class RequestAudit : IRequestAudit { public void Record(string path) { } }

// Convention-based middleware is a singleton: scoped services go in InvokeAsync, not the constructor.
public sealed class AuditMiddleware(RequestDelegate next)
{
    public async Task InvokeAsync(HttpContext context, IRequestAudit audit)
    {
        audit.Record(context.Request.Path);
        await next(context);
    }
}
// MVC equivalent: [FromServices] for a dependency only one action needs.
[ApiController, Route("api/reports")]
public sealed class ReportsController : ControllerBase
{
    [HttpGet("gst")]
    public IActionResult Gst([FromServices] IGstReportBuilder builder) => Ok(builder.Build());
}

⚠ Common mistakes

  • Mistake: Injecting a scoped service into a convention-based middleware constructor. Why it is wrong: middleware is created once, so the scoped instance is captured for the app's lifetime. Instead: take it as an InvokeAsync parameter, or implement IMiddleware.
  • Mistake: Adding settable properties for dependencies and expecting the built-in container to fill them. Why it is wrong: it only does constructor injection; the properties stay null. Instead: use constructor parameters.
  • Mistake: Reaching for property injection to shorten a long constructor. Why it is wrong: it hides the smell instead of fixing it. Instead: split responsibilities or introduce a facade.
  • Mistake: Overusing [FromServices] so that every action declares its own services. Why it is wrong: dependencies become scattered across action signatures and the controller's real dependencies are hard to see. Instead: use [FromServices] deliberately for a dependency that only one or two actions need (an expensive report builder, for example) and keep shared dependencies in the constructor.
  • Mistake: Making optional dependencies nullable and checking for null everywhere. Why it is wrong: it spreads conditional logic. Instead: register a null object or a default with TryAdd.
  • Mistake: Testing a property-injected class without setting every property. Why it is wrong: the test compiles and then throws NullReferenceException, or silently skips behaviour. Instead: prefer constructor injection so the compiler forces every dependency to be supplied.
  • Mistake: Assigning injected dependencies to mutable public properties. Why it is wrong: anyone can replace them later. Instead: keep them in readonly fields or primary constructor parameters.

🏛 Senior insight: trade-offs

The senior view is that the injection style is a design decision, not a container feature. Constructor injection keeps objects valid and makes tests trivial: new InvoiceService(fakeRepo, fakeClock) with no container and no setup order to remember. Property injection makes tests fragile, because a test that forgets to set a property compiles and fails at run time. Method injection is the right call when the dependency genuinely varies per call or only one operation needs it, for example passing a CancellationToken, an IProgress<T> or a per-request strategy into a single method instead of storing it in the object.

Performance is a non-issue for the choice: after warm-up the container resolves constructor graphs with compiled delegates, and framework method injection is a lookup in the request scope. What matters is clarity and lifetime correctness, especially in middleware.

Option When it fits Cost When not to
Constructor injection Required dependencies, almost every service Long constructors become visible Values that vary per call
Method injection (parameters, [FromServices], InvokeAsync) One operation needs it, per-call values, singleton middleware needing scoped services Callers must supply it each time; can scatter dependencies if overused Dependencies used by most methods of the class
Property injection (@inject, [Inject], Autofac) Framework-created components, truly optional extras Temporal coupling, harder tests Required dependencies in your own services

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions how the container picks the constructor Why: Checks deeper knowledge of constructor selection and ActivatorUtilities
    How to answer

    When you resolve a service, Microsoft.Extensions.DependencyInjection builds a call site: a tree describing how to create it (which constructor, which dependencies, which lifetime cache). It picks the constructor with the most parameters it can satisfy, and throws an InvalidOperationException if two equally long constructors are both satisfiable.

    Call sites are cached per service type. Early resolutions are interpreted; once a service has been resolved repeatedly it is compiled in the background to an expression-tree or IL delegate, so later resolutions are a delegate call plus lifetime lookups.

    GetService returns null for an unregistered type and GetRequiredService throws. ActivatorUtilities.CreateInstance builds a type that isn't registered, filling some constructor parameters from the container and others from arguments you pass.

    The trade-off: the built-in container is fast and predictable but deliberately minimal.

  2. When: Candidate mentions middleware and InvokeAsync Why: Checks convention-based middleware versus IMiddleware and their lifetimes
    How to answer

    Middleware is a component in the request pipeline: a RequestDelegate that receives the HttpContext, can do work, calls next to pass the request on, and can do more work when the response comes back. It can also short-circuit by not calling next. Use adds middleware that may call next; Run adds terminal middleware; Map branches the pipeline by path; UseWhen branches on a condition and rejoins, MapWhen branches without rejoining. Because each middleware wraps the next, order is behaviour: exception handling first, then HTTPS, static files, routing, CORS, authentication, authorisation and finally endpoints. Custom middleware can be convention-based (a class with InvokeAsync, created once as a singleton) or implement IMiddleware (resolved from DI per request). The trade-off: convention-based is the fastest default; IMiddleware is clearer when you need scoped dependencies.

  3. When: Candidate talks about optional dependencies Why: Checks using a Null Object instead of nullable or property-injected dependencies
    How to answer

    Null Object replaces null with an object that implements the same interface and does nothing safely, so callers don't need null checks.

    .NET uses it widely: NullLogger<T>.Instance, Stream.Null, TextWriter.Null, Array.Empty<T>(), Enumerable.Empty<T>(), Task.CompletedTask and CancellationToken.None. Returning an empty collection instead of null is the everyday form.

    Nullable reference types solve a different problem: they make "this might be null" visible at compile time so you handle it. Null Object is for when "do nothing" is genuinely the correct behaviour, like an optional logger.

    The danger is when doing nothing is wrong: a NullLogger left in production, or an empty list returned because the database call failed. Then the null object hides an error instead of preventing one.

↩ Usually asked after

More in DI Core Concepts

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me