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

📚 Interview question

How would you decorate every IRepository<T> with a caching decorator using the built-in container only, without Scrutor?

Decorating an open generic service such as IRepository<T> in Microsoft.Extensions.DependencyInjection without Scrutor, by closing the types yourself, and the performance and AOT trade-offs.

Mid-Level Theory Intermediate activatorutilities decorator-pattern dependency-injection open-generics scrutor

🎯 Key points

  • The built-in container has no open-generic factory or decorator support
  • Enumerate closed types (DbContext model, marker interface) and register per type
  • Register the inner implementation as its concrete closed type
  • Factory wraps the inner with the closed decorator type
  • Build ObjectFactory with ActivatorUtilities.CreateFactory once at start-up, not per resolution
  • Factories hide dependencies from ValidateOnBuild and the approach isn't AOT-safe; Scrutor or explicit registrations are often simpler

⏱ 30-second answer

Microsoft.Extensions.DependencyInjection (still in .NET 10) can't attach a factory or decorator to an open generic, so you close it yourself. Enumerate the entity types you use (from the DbContext model or a marker interface), and for each T register the inner EfRepository<T> as its concrete type, then register IRepository<T> with a factory that builds CachingRepository<T> around it. Do the reflection (MakeGenericType, ActivatorUtilities.CreateFactory) once at start-up and cache the resulting ObjectFactory, so each resolution is a delegate call rather than reflection. The costs: start-up work proportional to the number of entity types, factory registrations that ValidateOnBuild can't inspect, and code that isn't trimming/AOT-safe. For a handful of entities, explicit closed registrations are clearer; for many, Scrutor's Decorate(typeof(IRepository<>), typeof(CachingRepository<>)) is usually the better choice.

🔍 What the interviewer is checking

Checks whether they can work around a container limit by closing types themselves

↩ Usually asked after

More in Advanced DI

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me