如何使用Microsoft.Extensions.DependencyInjection注册装饰器?

byt*_*dev 5 dependency-injection ioc-container .net-core

使用Microsoft.Extensions.DependencyInjection作为容器时,如何注册装饰类?

以以下方式注册我的类型(类似于Castle Windsor)时,在解决IMyService类型时收到“ System.InvalidOperationException:检测到循环依赖”错误:

services.AddSingleton<IMyService, MyService>();
services.AddSingleton<IMyService, MyServiceDecorator>();
Run Code Online (Sandbox Code Playgroud)

装饰器注册似乎不被支持,但是有什么方法可以增加支持或解决问题?

byt*_*dev 5

使用Scrutor项目以以下方式注册似乎可以使装饰器正确解析:

services.AddSingleton<IMyService, MyService>();
services.Decorate<IMyService, MyServiceDecorator>();
Run Code Online (Sandbox Code Playgroud)

装饰是命名空间中的扩展方法:Scrutor项目中的Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions。

  • 装饰不是Microsoft提供的一种方法。 (2认同)