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
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();