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

πŸ“š Interview question

What is the Proxy pattern? Explain virtual, remote and protection proxies, and how EF Core lazy-loading proxies, DispatchProxy and Castle DynamicProxy implement it. What are the risks of proxies you can't see in the code?

Proxy intent and kinds (virtual, remote, protection, smart reference), EF Core lazy-loading proxies (virtual navigations, Castle, N+1, disposed-context errors), DispatchProxy for interfaces (and its AOT limits), Castle DynamicProxy interceptors, generated HTTP/gRPC clients, and the cost of invisible behaviour.

Mid-Level Theory Intermediate aop design-patterns dispatchproxy ef-core lazy-loading proxy

🎯 Key points

  • Proxy has the same interface as the real subject and controls access to it: when it's created, where it lives, or who may call it
  • Virtual proxy defers creating an expensive object (Lazy<T>, EF Core lazy-loading proxies); remote proxy hides a network call (gRPC client stubs, Refit/Kiota HTTP clients); protection proxy checks permissions before delegating
  • EF Core proxies (UseLazyLoadingProxies, Microsoft.EntityFrameworkCore.Proxies) generate subclasses via Castle; navigations must be virtual and entities non-sealed
  • Lazy loading hides queries: a loop over orders touching order.Customer issues N+1 queries; access after the DbContext is disposed throws
  • DispatchProxy.Create<TInterface, TProxy>() builds interface proxies at run time by overriding Invoke(MethodInfo, object[]); it uses Reflection.Emit, so it's not NativeAOT-compatible, and async methods need care
  • Castle DynamicProxy proxies interfaces and virtual class members with IInterceptor; Moq and NSubstitute use it
  • Proxy vs Decorator: same structure; a proxy controls access to the subject, a decorator adds features, and proxies often manage the subject's lifecycle
  • Risks: hidden I/O and latency, surprising exceptions, harder debugging, reflection cost and trimming/AOT incompatibility; prefer explicit loading or source-generated clients

⏱ 30-second answer

A Proxy has the same interface as the real object and controls access to it:

  • A virtual proxy delays creating something expensive: Lazy<T>, and EF Core lazy-loading proxies that load a navigation on first access.
  • A remote proxy makes a network call look like a local call: gRPC stubs, Refit or Kiota clients.
  • A protection proxy checks permissions before delegating.

.NET builds proxies at run time. EF Core generates subclasses through Castle, so navigations must be virtual. DispatchProxy creates interface proxies through Invoke(MethodInfo, args), but it uses Reflection.Emit and so isn't AOT-friendly. Castle DynamicProxy powers Moq and NSubstitute.

The trade-off is invisible behaviour. Code that looks like a property read can run a query (N+1), throw after the context is disposed, or make a network call.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"A proxy is a stand-in with the same interface as the real object that controls access to it. The client thinks it's talking to the real thing. There are a few classic kinds. A virtual proxy delays creating something expensive until it's actually used: Lazy<T> is a tiny one, and EF Core's lazy-loading proxies are the famous one. A remote proxy makes a call over the network look like a local method call. A gRPC client stub or a Refit-generated HTTP client are remote proxies. A protection proxy checks permissions before forwarding to the real object.

In .NET most proxies are generated at run time. EF Core's UseLazyLoadingProxies() uses Castle DynamicProxy to generate a subclass of each entity that overrides the virtual navigation properties. The first time you read order.Customer, the override runs a query. That's why navigations must be virtual and entities can't be sealed. DispatchProxy in the base library creates a proxy for an interface: you override Invoke(MethodInfo, object[]) and decide what to do with each call, which is handy for logging or remoting. It relies on Reflection.Emit, though, so it doesn't work under NativeAOT, and async methods return a Task you have to handle carefully. Castle DynamicProxy is the more powerful general tool, with interceptors on interfaces and virtual members, and it's what Moq and NSubstitute use underneath.

The mistake I see is forgetting that a proxy hides work. A foreach over 200 orders that reads order.Customer.Name looks innocent and issues 201 queries. Read it after the DbContext is disposed and it throws. A remote proxy hides latency and failures behind a method call. So in hot paths I prefer explicit loading with Include or projection, and source-generated clients over runtime magic. If a property read can hit the database, it should be obvious from the code."


Kinds of proxy

Kind Controls .NET example
Virtual When the real object is created or loaded Lazy<T>, EF Core lazy-loading proxies
Remote Where the object lives gRPC client stubs, Refit/Kiota/NSwag clients, WCF client proxies
Protection Who may call it Authorisation wrapper around a service
Smart reference Extra bookkeeping on access Ref counting, change-tracking proxies (UseChangeTrackingProxies)

How .NET generates proxies

Mechanism Proxies How AOT/trimming
Hand-written class Anything Implements the interface Fine
DispatchProxy Interfaces only Reflection.Emit, override Invoke Not supported in NativeAOT
Castle DynamicProxy Interfaces, virtual class members Reflection.Emit, IInterceptor Not AOT-friendly
Source generators (Refit, gRPC) Interfaces Generated at compile time Friendly

Production example

An orders page enabled EF Core lazy-loading proxies "for convenience". Rendering 100 orders with customer and line items produced about 300 queries per request, and p95 latency was 1.4 s. Disabling lazy loading and using a projection (Select into a DTO with the needed fields) cut it to one query and p95 to about 60 ms.

πŸ” What the interviewer is checking

Checks understanding of the kinds of proxy, how .NET generates them, and awareness of the performance and correctness risks of hidden behaviour.

Green flags

  • Names virtual, remote and protection proxies with .NET examples.
  • Explains how EF Core lazy-loading proxies work (virtual, Castle) and the N+1 risk.
  • Knows DispatchProxy's limits (interfaces, reflection, AOT, async).
  • Distinguishes Proxy from Decorator by intent.

Red flags

  • Recommends lazy loading everywhere.
  • Doesn't realise a property access can run a query.
  • Can't explain how mocking libraries create fakes.

πŸ“š Learn in depth

1. Structure

Client ──▢ Β«interfaceΒ» ISubject
               + Request()
            β–²              β–²
       RealSubject      Proxy ── realSubject (may be null until needed)
                        Request() { check / create / connect; realSubject.Request(); }

The structure is identical to Decorator. The difference is intent: a proxy controls access to its subject and often manages its lifecycle (creating it lazily, connecting to it remotely); a decorator adds behaviour to an object it is given.

2. EF Core lazy-loading proxies

  • Package Microsoft.EntityFrameworkCore.Proxies, optionsBuilder.UseLazyLoadingProxies().
  • At model build time EF generates, via Castle, a subclass Castle.Proxies.OrderProxy : Order that overrides each virtual navigation getter.
  • The override asks the context's lazy loader to load the navigation if it isn't loaded yet, then returns it.
  • If the context is disposed, EF raises the LazyLoadOnDisposedContextWarning, which by default throws an InvalidOperationException.
  • The alternative without proxies is injecting ILazyLoader into entities, which is still lazy loading, just explicit.

N+1 example: foreach (var o in orders) total += o.Customer.CreditLimit; runs 1 query for orders + N for customers. Fix with Include(o => o.Customer), a projection, or split queries.

3. DispatchProxy

public class LoggingProxy<T> : DispatchProxy where T : class
{
    public T Target { get; set; } = default!;
    protected override object? Invoke(MethodInfo? method, object?[]? args) => method!.Invoke(Target, args);
}
T proxy = DispatchProxy.Create<T, LoggingProxy<T>>();
  • Interfaces only; the proxy type must be non-sealed with a parameterless constructor.
  • method.Invoke uses reflection (slower, wraps exceptions in TargetInvocationException, so unwrap them).
  • For async methods Invoke returns the Task immediately; to log completion you must attach a continuation or await a generic helper.
  • Uses Reflection.Emit, so it's incompatible with NativeAOT.

4. Castle DynamicProxy

ProxyGenerator.CreateInterfaceProxyWithTarget(target, interceptors) or CreateClassProxy<T>() for virtual members. Interceptors implement IInterceptor.Intercept(IInvocation) and call invocation.Proceed(). Used by Moq, NSubstitute, EF Core proxies, and some AOP and DI interception libraries.

5. Remote proxies

A gRPC client generated from a .proto file exposes methods like GetOrderAsync(request) that serialise to Protobuf and send over HTTP/2. Refit turns an annotated interface into an HTTP client (source-generated). Treat every remote proxy call as a network call: timeouts, retries, cancellation and failure modes apply even though it looks local.

Try it yourself

  1. Enable UseLazyLoadingProxies, log SQL with LogTo(Console.WriteLine), and loop over 20 orders touching Customer. Count queries.
  2. Access a lazy navigation after disposing the context and read the error.
  3. Write a DispatchProxy that times calls, including async ones.
  4. Publish a small app with PublishAot=true that uses DispatchProxy and read the warnings.

πŸ’» Code

A protection proxy written by hand, and a timing DispatchProxy that handles async methods:

namespace Documents;

using System.Diagnostics;
using System.Reflection;

public interface IDocumentStore
{
    Task<byte[]> ReadAsync(Guid documentId, CancellationToken ct);
}

// Protection proxy: same interface, checks access before delegating
public sealed class AuthorisedDocumentStore(IDocumentStore inner, ICurrentUser user, IDocumentAcl acl) : IDocumentStore
{
    public async Task<byte[]> ReadAsync(Guid documentId, CancellationToken ct)
    {
        if (!await acl.CanReadAsync(user.Id, documentId, ct))
            throw new UnauthorizedAccessException($"User {user.Id} cannot read document {documentId}.");
        return await inner.ReadAsync(documentId, ct);
    }
}

// Runtime-generated proxy: works for any interface (not NativeAOT-compatible)
public class TimingProxy<T> : DispatchProxy where T : class
{
    private T _target = default!;
    private Action<string, TimeSpan> _report = (_, _) => { };

    public static T Wrap(T target, Action<string, TimeSpan> report)
    {
        T proxy = Create<T, TimingProxy<T>>();
        var self = (TimingProxy<T>)(object)proxy;
        self._target = target;
        self._report = report;
        return proxy;
    }

    protected override object? Invoke(MethodInfo? method, object?[]? args)
    {
        long start = Stopwatch.GetTimestamp();
        object? result;
        try
        {
            result = method!.Invoke(_target, args);
        }
        catch (TargetInvocationException ex) when (ex.InnerException is not null)
        {
            throw ex.InnerException;   // don't leak the reflection wrapper
        }

        if (result is Task task)       // async: report when the task completes, not when it is returned
        {
            task.ContinueWith(_ => _report(method.Name, Stopwatch.GetElapsedTime(start)), TaskScheduler.Default);
            return result;
        }
        _report(method.Name, Stopwatch.GetElapsedTime(start));
        return result;
    }
}
// Virtual proxy you can avoid: replace lazy loading with an explicit projection
namespace Orders;

public sealed record OrderRow(Guid Id, string CustomerName, decimal Total);

public static class OrderQueries
{
    public static Task<List<OrderRow>> RecentAsync(AppDbContext db, CancellationToken ct) =>
        db.Orders
          .OrderByDescending(o => o.PlacedAt)
          .Take(100)
          .Select(o => new OrderRow(o.Id, o.Customer.Name, o.Total))   // one SQL query with a JOIN, no proxies
          .ToListAsync(ct);
}

⚠ Common mistakes

  • Mistake: Turning on EF Core lazy-loading proxies globally for convenience. Why it is wrong: Every navigation access in a loop becomes a query (N+1), and latency scales with result size. Instead: Use Include, projections or explicit loading; keep lazy loading off by default.
  • Mistake: Returning lazy-loading entities from an API and letting the serialiser walk them. Why it is wrong: Serialisation triggers queries for every navigation, may hit a disposed context, and can loop on cycles. Instead: Project to DTOs.
  • Mistake: Making entities sealed or navigations non-virtual and wondering why lazy loading does nothing. Why it is wrong: Castle can only override virtual members of non-sealed classes. Instead: Know the requirement, or (better) don't depend on lazy loading.
  • Mistake: Using DispatchProxy or Castle in an app targeting NativeAOT or aggressive trimming. Why it is wrong: Reflection.Emit isn't available; it fails at run time. Instead: Hand-written decorators or source generators.
  • Mistake: Letting TargetInvocationException escape from a reflection-based proxy. Why it is wrong: Callers' catch blocks for the real exception type never match. Instead: Unwrap InnerException (or use ExceptionDispatchInfo.Throw).
  • Mistake: Treating a remote proxy call like a local call. Why it is wrong: It can be slow, fail or time out; no cancellation means hung requests. Instead: Pass CancellationToken, set timeouts, and add resilience.
  • Mistake: Measuring async methods in a proxy at the moment Invoke returns. Why it is wrong: It records the time to create the task, not the operation. Instead: Attach a continuation or await in a generic helper.

πŸ› Senior insight: trade-offs

Proxies are powerful because they're invisible, and dangerous for the same reason. My rule: invisible behaviour must be cheap and safe. Lazy loading that turns a property read into a database round trip fails that test in most web APIs, so I keep it off and make data loading explicit. Remote proxies are fine as long as the team treats them as network calls.

Option When it fits Cost When not to
Hand-written proxy One interface, clear purpose (authorisation, lazy creation) A class Many interfaces needing the same thing
EF Core lazy loading Small admin tools, rich object graphs navigated rarely Hidden queries, N+1 APIs, hot paths, serialisation
DispatchProxy Cross-cutting concern over many interfaces, JIT-only Reflection cost, async complexity NativeAOT, hot paths
Source-generated client (Refit, gRPC) Remote calls Build-time tooling β€”

To detect hidden proxy costs I log SQL in development (LogTo), watch query counts per request in Application Insights dependency telemetry, and set a per-request query budget in integration tests.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate says proxy and decorator look the same Why: Checks the difference between Proxy and Decorator
    How to answer

    Decorator wraps an object in another object that implements the same interface, adds behaviour before or after delegating, and is invisible to callers. Decorators stack: logging around caching around the real repository. Each concern is one small class, so the original stays untouched (Open/Closed).

    .NET uses it everywhere: GZipStream(BufferedStream(FileStream)), CryptoStream, and DelegatingHandler pipelines in HttpClient.

    The built-in container has no Decorate method. You register the inner type concretely and the interface with a factory delegate, use a keyed inner service, or use Scrutor's Decorate<TService, TDecorator>().

    The trade-off is that order matters and long chains are harder to debug.

  2. When: Candidate says EF Core proxies need virtual navigations Why: Checks virtual dispatch, which runtime proxies depend on
    How to answer

    A virtual member can be overridden by a derived class, and a call to it is resolved by the run-time type of the object, not the variable's type. In C#, members are non-virtual by default (unlike Java), because every virtual member is a promise to subclasses and is harder to change. At run time the call loads the object's method table, reads the method's slot and calls through it, which prevents inlining unless the JIT can devirtualise (exact type known, sealed class or method, or dynamic PGO's guarded devirtualisation). Methods, properties, indexers and events can be virtual; static (outside interfaces), private and constructors cannot.

πŸ›  Real-world problems: how you handle them

Lazy-loading proxies turned an orders page into 300 queries per request
Situation
An internal order management API on .NET [10] with EF Core and Azure SQL, used by [~400] staff. A developer enabled `UseLazyLoadingProxies()` to fix a null navigation bug.
Signals
p95 latency on `GET /orders` rose from [80 ms] to [1.4 s] after the release; Azure SQL showed a [6×] increase in batch requests per second; Application Insights showed [~300] SQL dependency calls per request.
Investigation
Opened one slow request's end-to-end transaction in Application Insights: hundreds of near-identical `SELECT ... FROM Customers WHERE Id = @p` calls. Logged SQL locally with `LogTo` and saw the JSON serialiser touching `Customer` and `Lines` navigations for every order. The release diff showed `UseLazyLoadingProxies()` added globally.
Resolution
Immediate: reverted the lazy-loading change and fixed the original null navigation with `Include`. Real fix: changed the endpoint to project into a DTO with `Select`, producing one query with joins.
Prevention
Integration test asserting a query budget per endpoint (counting commands via an EF Core interceptor); a rule against returning entities from APIs; lazy loading banned in the API project by an architecture test.

How to tell it (STAR)

**S:** At [company] our orders page went from [80 ms] to [1.4 seconds] at p95 after a small release. **T:** I was asked to find the regression. **A:** Application Insights showed [~300] SQL calls for a single request, almost all identical customer and line-item lookups. The release had enabled EF Core lazy-loading proxies to fix a null navigation, so the JSON serialiser was triggering a query for every navigation on every order. I reverted that, fixed the original bug with `Include`, and changed the endpoint to project into a DTO. **R:** It dropped to one query and [~60 ms] at p95, database load fell by [~80%], and a query-budget test now fails the build if an endpoint goes over [5] queries.

↩ Usually asked after

More in Structural Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me