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.
A Proxy has the same interface as the real object and controls access to it:
Lazy<T>, and EF Core lazy-loading proxies that load a navigation on first access..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.
"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 thevirtualnavigation properties. The first time you readorder.Customer, the override runs a query. That's why navigations must be virtual and entities can't be sealed.DispatchProxyin the base library creates a proxy for an interface: you overrideInvoke(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 aTaskyou 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
foreachover 200 orders that readsorder.Customer.Namelooks innocent and issues 201 queries. Read it after theDbContextis disposed and it throws. A remote proxy hides latency and failures behind a method call. So in hot paths I prefer explicit loading withIncludeor projection, and source-generated clients over runtime magic. If a property read can hit the database, it should be obvious from the code."
| 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) |
| 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 |
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.
Checks understanding of the kinds of proxy, how .NET generates them, and awareness of the performance and correctness risks of hidden behaviour.
Green flags
DispatchProxy's limits (interfaces, reflection, AOT, async).Red flags
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.
Microsoft.EntityFrameworkCore.Proxies, optionsBuilder.UseLazyLoadingProxies().Castle.Proxies.OrderProxy : Order that overrides each virtual navigation getter.LazyLoadOnDisposedContextWarning, which by default throws an InvalidOperationException.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.
DispatchProxypublic 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>>();
method.Invoke uses reflection (slower, wraps exceptions in TargetInvocationException, so unwrap them).Invoke returns the Task immediately; to log completion you must attach a continuation or await a generic helper.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.
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.
UseLazyLoadingProxies, log SQL with LogTo(Console.WriteLine), and loop over 20 orders touching Customer. Count queries.DispatchProxy that times calls, including async ones.PublishAot=true that uses DispatchProxy and read the warnings.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);
}
Include, projections or explicit loading; keep lazy loading off by default.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.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.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).CancellationToken, set timeouts, and add resilience.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.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.
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.
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.
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.
Last updated 18 Nov 2026.