简体   繁体   中英

Unable to add a singleton service due to serviceProvider.GetService<IRabbitMQConsumer>() returning null

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
    }
}

You need to configure the ServiceCollection before you call BuildServiceProvider .

In your case, you should move the IServiceProvider serviceProvider = services.BuildServiceProvider(); line down below startup.ConfigureServices(services, logger);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM