Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

.Net 8 Console App DI Error 'Unable to resolve service for type 'Microsoft.Extensions.Logging.ILoggerFactory'

I’m trying to add dependency injection to a .Net 8 Console Application following the explanation in this video How to use Dependency Injection (DI) in C# Console Application with Logging but I get the following error:

"Unable to resolve service for type ‘Microsoft.Extensions.Logging.ILoggerFactory’ while attempting to activate ‘Microsoft.Extensions.Localization.ResourceManagerStringLocalizerFactory’."

This is the code of the Program.cs

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ServiceCollection services = new();

services.AddLocalization(options => options.ResourcesPath = "Localization");

services.AddSingleton<ILocalizationService, LocalizationService>();
services.AddScoped<IEntityService, EntityService>();

var provider = services.BuildServiceProvider();

EntityService service = new(provider.GetService<ILocalizationService>());

This is the code of the LocalizationService class

public class LocalizationService : ILocalizationService
{
public class SharedResource { }

private readonly IStringLocalizer _localizer;
public LocalizationService(IStringLocalizerFactory factory)
{
    var type = typeof(SharedResource);
    var assemblyName = new AssemblyName(type.GetTypeInfo().Assembly.FullName!);
    _localizer = factory.Create("Resource", assemblyName.Name!);
}
public LocalizedString GetKey(string key)
{
    return _localizer[key];
}
}

This is the Entity Service class

public class EntityService(ILocalizationService localization) : IEntityService
{
   ...
}

The error occurs at this line of the Program.cs

EntityService service = new(provider.GetService<ILocalizationService>());

I tried a lot of solutions found on stack overflow but nothing helped and don’t need the logging.

How to fix this error?

>Solution :

ResourceManagerStringLocalizerFactory depends on Microsoft.Extensions.Logging.ILoggerFactory which is required for service to be resolved via DI.

You are missing LoggingServiceCollectionExtensions.AddLogging call. For example add Microsoft.Extensions.Logging.Console nuget:

services.AddLogging(lb => lb.AddConsole());

If you don’t want actual logging then Microsoft.Extensions.Logging is sufficient with the following registration:

services.AddLogging();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading