How to apply decorators with ASP.NET Core Dependency Injection

The out of the box IoC container doesn't support decorate pattern or auto discovery, which is "by design" as far as I know.

The idea is to provide a basic IoC structure that works out of the box or where other IoC containers can be plugged in to extend the default functionality.

So if you need any advanced features (support for a specific constructor, auto-registering of all types which implement an interface or inject decorators and interceptors) you have to either write it yourself or use an IoC container which offers this functionality.


Use Scrutor. Just install the nuget package and then do the following.

services.AddSingleton<IGreeter, Greeter>();
services.Decorate<IGreeter, GreeterLogger>();
services.Decorate<IGreeter, GreeterExceptionHandler>();

The order is important. In the above, GreeterLogger decorates Greeter. And GreeterExceptionHandler decorates GreeterLogger.

If you need more info, take a look at this and this.

And of course, you can use the popular Autofac as well.

If you want to know how to configure Autofac, take a look at Ardalis Clean Arch template