ASP.NET Core: System.AggregateException HResult=0x80131500 Message=Some services are not able to be constructed

  Kiến thức lập trình

In ASP.NET Core Worker Windows Service with RabbitMQ, MSSQL, Dapper and Repository, and Serilog, I am given a Queue to consume.
I want to consume the Queue, Acknowledge and remove it.

I got this error:

System.AggregateException
HResult=0x80131500
Message=Some services are not able to be constructed (Error while validating the service descriptor ‘ServiceType: Microsoft.Extensions.Hosting.IHostedService Lifetime: Singleton ImplementationType: NIPIncomingStatusVerification_Queue.Worker’: Unable to resolve service for type ‘NIPIncomingStatusVerification_Queue.Utilities.ApplicationSettings’ while attempting to activate ‘NIPIncomingStatusVerification_Queue.Repositories.Implementations.NIPIncomingStatusVerificationQueueRepository’.) (Error while validating the service descriptor ‘ServiceType: NIPIncomingStatusVerification_Queue.Helpers.Common.IRabbitMQManager Lifetime: Singleton ImplementationType: NIPIncomingStatusVerification_Queue.Helpers.Common.RabbitMQManager’: Unable to resolve service for type ‘NIPIncomingStatusVerification_Queue.Utilities.ApplicationSettings’ while attempting to activate ‘NIPIncomingStatusVerification_Queue.Repositories.Implementations.NIPIncomingStatusVerificationQueueRepository’.) (Error while validating the service descriptor ‘ServiceType: NIPIncomingStatusVerification_Queue.Repositories.Interfaces.INIPIncomingStatusVerificationQueueRepository Lifetime: Singleton ImplementationType: NIPIncomingStatusVerification_Queue.Repositories.Implementations.NIPIncomingStatusVerificationQueueRepository’: Unable to resolve service for type ‘NIPIncomingStatusVerification_Queue.Utilities.ApplicationSettings’ while attempting to activate ‘NIPIncomingStatusVerification_Queue.Repositories.Implementations.NIPIncomingStatusVerificationQueueRepository’.) (Error while validating the service descriptor ‘ServiceType: NIPIncomingStatusVerification_Queue.Services.Interfaces.INIPIncomingStatusVerificationQueueService Lifetime: Singleton ImplementationType: NIPIncomingStatusVerification_Queue.Services.Implementations.NIPIncomingStatusVerificationQueueService’: Unable to resolve service for type ‘NIPIncomingStatusVerification_Queue.Utilities.ApplicationSettings’ while attempting to activate ‘NIPIncomingStatusVerification_Queue.Repositories.Implementations.NIPIncomingStatusVerificationQueueRepository’.)
Source=Microsoft.Extensions.DependencyInjection
StackTrace:
at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection1 serviceDescriptors, ServiceProviderOptions options) at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options) at Microsoft.Extensions.Hosting.Internal.ServiceFactoryAdapter1.CreateServiceProvider(Object containerBuilder)
at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
at Microsoft.Extensions.Hosting.HostBuilder.Build()
at Program.d__1.MoveNext() in C:NIPIncomingStatusVerification-QueueProgram.cs:line 15
at Program.(String[] args)

This exception was originally thrown at this call stack:

[Call Stack Truncated]

Inner Exception 1:
InvalidOperationException: Error while validating the service descriptor ‘ServiceType: Microsoft.Extensions.Hosting.IHostedService Lifetime: Singleton ImplementationType: NIPIncomingStatusVerification_Queue.Worker’: Unable to resolve service for type ‘NIPIncomingStatusVerification_Queue.Utilities.ApplicationSettings’ while attempting to activate ‘NIPIncomingStatusVerification_Queue.Repositories.Implementations.NIPIncomingStatusVerificationQueueRepository’.

Inner Exception 2:
InvalidOperationException: Unable to resolve service for type ‘NIPIncomingStatusVerification_Queue.Utilities.ApplicationSettings’ while attempting to activate ‘NIPIncomingStatusVerification_Queue.Repositories.Implementations.NIPIncomingStatusVerificationQueueRepository’.

This is Program.cs Line 15:

IHost host = Host.CreateDefaultBuilder(args)

Kindly help resolve it.

MAIN CODE:

appsettings.json:

{
  "FilePath": "logs//",
  "ConnectionStrings": {
    "DefaultConnection": ""
  },
  "AllowedHosts": "*",
  "CIBSettings": {
    "NIBBSRoutingInstitutionCode": "876543",
  },
  "RabbitMQ": {
    "RMQUsername": "",
    "RMQPassword": "",
    "RMQHost": "",
    "RMQPort": 0987,
    "QueueName": "E",
    "DelayTimeSpanInSeconds": 20,
    "RMQFetchCount": 20,
    "RMQAutoAck": false,
    "ThreadWorker": 100,
    "CompletionThread": 10
  }
}

Program.cs:

public class Program
{
    private static IConfiguration configuration = null!;
 
    static async Task Main(string[] args)
    {
        IHost host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging((hostContext, logging) =>
            {
                configuration = hostContext.Configuration;
             //   string path = Path.Combine(configuration.GetValue<string>("FilePath"), "NIP_Incoming_StatusVerificationService_Queue-{Date}.log");
                string path = Path.Combine(new ApplicationSettings(hostContext.Configuration).GetFilePath(), "NIP_Incoming_StatusVerificationService_Queue-{Date}.log");
 
                Log.Logger = new LoggerConfiguration()
                    .MinimumLevel.Information()
                    .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                    .Enrich.FromLogContext()
                    .WriteTo.Console()
                    .WriteTo.RollingFile(path)
                    .CreateLogger();
                logging.AddSerilog();
            })
            .ConfigureServices((hostContext, services) =>
            {
                services.Configure<ApplicationSettings>(hostContext.Configuration.GetSection(nameof(ApplicationSettings)));
                services.AddHostedService<Worker>();
 
                services.AddSingleton<IRabbitMQManager, RabbitMQManager>();
                services.AddDIServices(configuration);
            })
            .UseSerilog()
            .UseWindowsService()
            .Build();
 
        await host.RunAsync();
    }
}

Extension:

public static class DIServiceExtension
{
    public static void AddDIServices(this IServiceCollection services, IConfiguration configuration)
    {
        services.AddSingleton<INIPIncomingStatusVerificationQueueRepository, NIPIncomingStatusVerificationQueueRepository>();
        services.AddSingleton<INIPIncomingStatusVerificationQueueService, NIPIncomingStatusVerificationQueueService>();
    }
}

ApplicationSettings:

public class ApplicationSettings
{
    private readonly IConfiguration _configuration;
    public ApplicationSettings(IConfiguration configuration)
    {
        _configuration = configuration;
    }
    public RabbitMQSettings GetRabbitMQSettings()
    {
        var rabbitMQSection = _configuration.GetSection("RabbitMQ");
        return rabbitMQSection.Get<RabbitMQSettings>();
    }
    public CIBSettings GetCIBSettings()
    {
        var cibSection = _configuration.GetSection("CIBSettings");
        return cibSection.Get<CIBSettings>();
    }
    public string GetFilePath()
    {
        return _configuration.GetValue<string>("FilePath");
    }
    public string GetConnectionString()
    {
        return _configuration.GetConnectionString("DefaultConnection");
    }

}
public class RabbitMQSettings
{
    public string RMQUsername { get; set; }
    public string RMQPassword { get; set; }
    public string RMQHost { get; set; }
    public int RMQPort { get; set; }
    public string QueueName { get; set; }
    public int DelayTimeSpanInSeconds { get; set; }
    public int RMQFetchCount { get; set; }
    public bool RMQAutoAck { get; set; }
    public int ThreadWorker { get; set; }
    public int CompletionThread { get; set; }
}
public class CIBSettings
{
    public string NIBBSRoutingInstitutionCode { get; set; }
}

Repository:

public class NIPIncomingStatusVerificationQueueRepository : INIPIncomingStatusVerificationQueueRepository
{
    private readonly ApplicationSettings _appSettings;
    ILogger<NIPIncomingStatusVerificationQueueRepository> _logger;
    public NIPIncomingStatusVerificationQueueRepository(
      ApplicationSettings appSettings,
        ILogger<NIPIncomingStatusVerificationQueueRepository> logger
    )
    {
        _appSettings = appSettings;
        _logger = logger;
    }
        public IDbConnection Connection
    {
        get { return new SqlConnection(_appSettings.GetConnectionString()); }
    }
    ...
}

Service:

public class NIPIncomingStatusVerificationQueueService : INIPIncomingStatusVerificationQueueService
{
    private readonly INIPIncomingStatusVerificationQueueRepository _creditRequestRepository;
    private readonly ApplicationSettings _appSettings;
    ILogger<NIPIncomingStatusVerificationQueueService> _logger;
    public NIPIncomingStatusVerificationQueueService(
        INIPIncomingStatusVerificationQueueRepository creditRequestRepository,
      ApplicationSettings appSettings,
        ILogger<NIPIncomingStatusVerificationQueueService> logger
    )
    {
        _creditRequestRepository = creditRequestRepository;
        _appSettings = appSettings;
        _logger = logger;
    }
   ...
}

RabbitMQManager:

public class RabbitMQManager : IRabbitMQManager
{
    private readonly INIPIncomingStatusVerificationQueueService _creditRequestService;
    private readonly ILogger<RabbitMQManager> _logger;
    private readonly ApplicationSettings _appSettings;
    private IConnection _connection;
    private IModel channel = null;
    public RabbitMQManager(
        INIPIncomingStatusVerificationQueueService creditRequestService,
        ILogger<RabbitMQManager> logger,
        IOptions<ApplicationSettings> options
        )
    {
        _creditRequestService = creditRequestService;
        _appSettings = options.Value;
        _logger = logger;
    }
    ...
}

Worker:

public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;
    private readonly IRabbitMQManager _rabbitMQManager;
    public Worker(
        ILogger<Worker> logger,
        IRabbitMQManager rabbitMQManager
        )
    {
        _rabbitMQManager = rabbitMQManager;
        _logger = logger;
    }
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        try
        {
            _logger.LogInformation($"Worker started at: {DateTimeOffset.Now}");
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation($"Worker running at: {DateTimeOffset.Now}");
                await _rabbitMQManager.ListenToStatusVerificationMessage(stoppingToken);
                // Adjust the delay interval as needed
                await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);
            }
            _logger.LogInformation($"Worker stopped at: {DateTimeOffset.Now}");
        }
        catch (TaskCanceledException taskEx)
        {
            _logger.LogError($"TaskCanceledException: {taskEx.Message},n Stack Trace: {taskEx.StackTrace}, n Inner Exception: {taskEx.InnerException}");
        }
        catch (Exception ex)
        {
            _logger.LogError($"Exception: {ex.Message},n Stack Trace: {ex.StackTrace}, n Inner Exception: {ex.InnerException}");
            Environment.Exit(1);
        }
    }
}

LEAVE A COMMENT