dependency-injection.net-coreioc-container

How can I register a decorator using Microsoft.Extensions.DependencyInjection?


How can I register a decorator class when using Microsoft.Extensions.DependencyInjection as the container?

When registering my types in the following way (similar to Castle Windsor) I get a "System.InvalidOperationException : A circular dependency was detected" error on resolving the IMyService type:

services.AddSingleton<IMyService, MyService>();
services.AddSingleton<IMyService, MyServiceDecorator>();

Decorator registration does not appear to be supported out the box but is there any way to add support or get round the problem?


Solution

  • Registering in the following way using the Scrutor project appears to get the decorator to resolve correctly:

    services.AddSingleton<IMyService, MyService>();
    services.Decorate<IMyService, MyServiceDecorator>();
    

    Decorate is an extension method in the namespace: Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions within the Scrutor project.