How can the Decorator pattern be implemented using dependency injection in ASP.NET Core to add functionality to an existing service without modifying its core code?

.NET interview question for Advanced practice.

Answer

By creating decorator classes that implement the same interface as the original service, injecting the original service into the decorator's constructor, and then registering the decorator to resolve the interface.

Explanation

This correctly describes the implementation of the Decorator pattern with DI. You create a decorator class that implements the same interface (e.g., IService). The decorator's constructor takes the original IService as a dependency. You then register the concrete service and then register the decorator to provide the IService interface. The DI container will inject the concrete service into the decorator, and inject the decorator into the final consumer.

Related Questions