'How to solve Dependency injection and Inconsistent accessibility parameter type '' in .Net 3 Worker service?

I am setting a .Net core worker services that will get some data from the database and pass that to an endpoints. So I am trying to set it up base on my .net MVC knowledge. While setting up, I got this error:

Unhandled exception. System.ArgumentNullException: Value cannot be null. (Parameter 'implementationInstance') at Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton[TService](IServiceCollection services, TService implementationInstance

I created a class where the logic for fetch data from a stored procedure. This is the Business call:

namespace AgencyBankingSettlement.Business
{
    public class ServiceTask
    {
        private readonly AgencyBankingSettlementDbContext context;

        public ServiceTask(AgencyBankingSettlementDbContext _context)
        {
            context = _context;
        }
        public IEnumerable<Testing> Request() {
            var person = context.Testings.FromSqlRaw<Testing>("dbo.spPerson_GetAll");
            return person;
        }
    }
}

This is my program.cs. In the program.cs file I set up dependency injection so that I can easily inject into my classes and you it:

public static void Main(string[] args)
{
    CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureServices((hostContext, services) =>
        {
            IConfiguration configuration = hostContext.Configuration;

            AppSettings appSettings = configuration.GetSection("ContextCore").Get<AppSettings>();

            services.AddSingleton(appSettings);
            services.AddScoped<ServiceTask>();

            services.AddDbContext<AgencyBankingSettlementDbContext>(options =>
            options.UseSqlServer(hostContext.Configuration.GetConnectionString("DefaultConnection")));

            services.AddHostedService<Worker>();
        });

So in my worker.cs. I want to be able to access the ServiceTask file and log the "persons" information that will be injected from the serviceTask. I could not also access the file. If I can fix this then every other thing I want to do will also follow the same pattern.

public class Worker : BackgroundService
{
    private readonly ServiceTask serviceTask;
    private readonly ILogger<Worker> _logger;
    

    public Worker(ILogger<Worker> logger, ServiceTask _serviceTask)
    {
        serviceTask = _serviceTask;
        _logger = logger;
        
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            var persons = serviceTask.Request();
                _logger.LogInformation(persons);
            _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
            await Task.Delay(1000, stoppingToken);
        }
    }
}

How can I make this to work?



Solution 1:[1]

I have been able to fix that. the explanation is on this page Dependency Injection in ASP.NET Core Worker Service

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureServices((hostContext, services) =>
        {
            IConfiguration configuration = hostContext.Configuration;

            AppSettings appSettings = configuration.GetSection("DefaultConnection").Get<AppSettings>();

            //services.AddTransient(appSettings);
            //services.AddTransient<ServiceTask>();
            services.AddSingleton<ServiceTask>();

            services.AddDbContext<AgencyBankingSettlementDbContext>(options =>
            options.UseSqlServer(hostContext.Configuration.GetConnectionString("DefaultConnection")), ServiceLifetime.Singleton);

            services.AddHostedService<Worker>();
        });

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Axel Köhler