I am trying to add a singleton service of the type mentioned in IRabbitMQConsumer with an implementation type in RabbitMQConsumer to the Iservicecollection. But when I tried using below approach, I am receiving Null Reference exception as the GetService<ILoggerFactory> is returning null value.
This code was working when I was using .Net core 2.2 and appears as a problem when I have migrated to .Net core 3.1.12. I have tried many stack-overflow threads as below, where it seems to be correct but not sure why my code is throwing an exception. Resolving instances with ASP.NET Core DI from within ConfigureServices, How to Resolve Instance Inside ConfigureServices in ASP.NET Core Please find my code below and kindly help me to fix this problem as I am very beginner in these middle-wares.
#Program.cs
internal class Program
{
private static void Main(string[] args)
{
IServiceCollection services = new ServiceCollection();
IServiceProvider serviceProvider = services.BuildServiceProvider();
Startup startup = new Startup();
startup.ConfigureServices(services, logger);
//configure console logging
serviceProvider.GetService<ILoggerFactory>();
var logger = serviceProvider.GetService<ILoggerFactory>(); // logger returns null
//do the actual work here
var client = serviceProvider.GetService<IRabbitMQConsumer>(); // client returns null
client.CreateConnection();
client.ProcessMessages();
}
}
#startup.cs
public class Startup
{
private static readonly Logger _log = LogManager.GetCurrentClassLogger();
IConfigurationRoot Configuration { get; }
public Startup()
{
LogManager.LoadConfiguration(string.Concat(Directory.GetCurrentDirectory(), "/NLog.config"));
}
public void ConfigureServices(IServiceCollection services, ILoggerFactory loggerFactory)
{
loggerFactory.AddNLog(); // System.NullReferenceException
services.AddSingleton<IRabbitMQConsumer, RabbitMQConsumer>();// System.NullReferenceException
}
}