Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 223
bytedev Avatar asked Sep 28 '17 13:09

bytedev


1 Answers

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.

like image 117
bytedev Avatar answered Oct 14 '22 19:10

bytedev