khellang / Scrutor

Assembly scanning and decoration extensions for Microsoft.Extensions.DependencyInjection
MIT License
3.63k stars 239 forks source link

Not able to register ILogger with the decorater pattern #205

Open arpit2408 opened 1 year ago

arpit2408 commented 1 year ago

Hi @khellang trying to register my ILogger service like this:-

Method 1:

1: services.AddLogging();
2: services.Decorate<Extensions.Logging.ILogger, ExtensionsLoggerDecorator>();

It gives the following error at line 2:- image

Method 2:

1: services.AddLogging();
2: services.AddSingleton<Extensions.Logging.ILogger, Extensions.Logging.ILogger>();
3: services.Decorate<Extensions.Logging.ILogger, ExtensionsLoggerDecorator>();

It passes to line 3 but gives the following error at hostBuilder.build() image

Here is the definition of the ExtensionsLoggerDecorator class

public class ExtensionsLoggerDecorator : ILogger {
    // All interface classes implemented
}

I have installed the latest version https://www.nuget.org/packages/Scrutor and using .NET 6. I am trying to accomplish a wrapper/decorator for my ILogging implementation so that all logs pass through my custom class before getting logged by openTelemetry.

Please tell me what I am doing wrong here or is it a bug?

arpit2408 commented 1 year ago

I have looked at the answers here https://github.com/dotnet/runtime/issues/36021 but didn't help.

arpit2408 commented 1 year ago

The compile time error is resolved if I use the decorator like below:-

services.AddLogging();
services.Decorate(typeof(ILogger), typeof(ExtensionsLoggerDecorator));

But now the decorator function isn't called when I call _logger.logInformation and instead extensions.logger is called.