0

In a .Net 5 Web API, I'm trying to do logging in a scoped service.

I first tried to introduce the logger service via constructor dependency injection:

using Microsoft.Extensions.Logging; public class SmsService : ISmsService { private readonly ILogger _logger; public SmsService(ILogger logger) { _logger = logger; } } 

But when I run the API, I get this exception:

System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: PropWorx.API.Interfaces.ISmsService Lifetime: Scoped ImplementationType: PropWorx.API.Services.SmsService': Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger' while attempting to activate 'PropWorx.API.Services.SmsService'.)'

I then removed the dependency injection, and tried creating a scope at the point of logging:

private readonly IServiceProvider _serviceProvider; using (var scope = _serviceProvider.CreateScope()) { using (var logger = scope.ServiceProvider.GetRequiredService<ILogger>()) { logger.LogError("some error message"); } } 

But I get this compile time error:

CS1674 'ILogger': type used in a using statement must be implicitly convertible to 'System.IDisposable'.

Any ideas?

0

1 Answer 1

5

About your first try

The code seems legitimate. My guess is that you are not configuring the DI container with a concrete implementation of the ILogger so by the instantiation time, it does not know which object of ILogger type to create.

You can check here to see how to configure and add the default logging providers.

About your second try

The following is the definition of GetRequiredService

public static T GetRequiredService<T> (this IServiceProvider provider); 

You can see that it returns the T, in your case the ILogger interface. The created instance is not Disposable, so it can't be used in the using declaration.

Try using it this way:

using (var scope = _serviceProvider.CreateScope()) { var logger = scope.ServiceProvider.GetRequiredService<ILogger>(); logger.LogError("some error message"); } 

Please provide the injection configuration for ILogger (meaning the definition where you provide the concrete implementation of ILogger you are using, to help you with the first example.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - you were right on both counts. Regarding DI, instead of private readonly ILogger _logger; I used private readonly ILogger<SmsService> _logger; and the error went away. Regarding your second suggestion, I tried that and it also worked. Thank you! :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.