Value cannot be null. (Parameter 'context') at ResolveService() (v2023)

I am trying to create a background coordinate update process, the process performs well until the time to perform the data update procedure. See the code and error log belowCODE in C#

//public async Task AtualizarCoordenadasNoBancoDeDados(int idLocalidade, string lat, string lon, int taskId)
//{
//    _logger.LogInformation("Iniciando AtualizarCoordenadasNoBancoDeDados.");

//    try
//    {
//        _logger.LogInformation($"Iniciando atualização de coordenadas para localidade ID: {idLocalidade}");

//        // Crie um dicionário com os parâmetros da stored procedure
//        var parameters = new Dictionary<string, object>
//        {
//            ["@IDLocalidade"] = idLocalidade,
//            ["@Latitude"] = lat,
//            ["@Longitude"] = lon
//        };

//        // Execute a stored procedure
//        var result = await ExecuteStoredProcedure("sp_AtualizarCoordenadas", parameters);

//        if (result > 0)
//        {
//            _logger.LogInformation($"Localidade ID: {idLocalidade} - Coordenadas atualizadas com sucesso.");
//            UpdateTaskStatus(taskId, status => status.Steps.Add($"Coordenadas atualizadas para localidade ID: {idLocalidade}"));
//        }
//        else
//        {
//            _logger.LogWarning($"Nenhuma linha afetada ao atualizar coordenadas para localidade ID: {idLocalidade}");
//            UpdateTaskStatus(taskId, status => status.Steps.Add($"Falha ao atualizar coordenadas para localidade ID: {idLocalidade} - Nenhuma linha afetada"));
//        }
//    }
//    catch (Exception ex)
//    {
//        _logger.LogError(ex, $"Erro inesperado ao atualizar coordenadas para localidade ID: {idLocalidade}");
//        UpdateTaskStatus(taskId, status => status.Steps.Add($"Erro ao atualizar coordenadas para localidade ID: {idLocalidade} - {ex.Message}"));
//        throw;
//    }
//}

//// Método auxiliar para executar a stored procedure
//private async Task<int> ExecuteStoredProcedure(string procedureName, Dictionary<string, object> parameters)
//{

//    _logger.LogInformation("Iniciando ExecuteStoredProcedure.");

//    var connection = await GetConnectionAsync();

//    if (Conn == null)
//    {
//        _logger.LogInformation("Não foi possível obter uma conexão válida.");
//        throw new InvalidOperationException("Não foi possível obter uma conexão válida.");
//    }

//    _logger.LogInformation($"Procedure Name:{procedureName} - Parameters:{parameters}");

//    using (var command = connection.CreateCommand())
//    {
//        command.CommandType = CommandType.StoredProcedure;
//        command.CommandText = procedureName;

//        foreach (var param in parameters)
//        {
//            command.Parameters.AddWithValue(param.Key, param.Value);
//        }

//        return await command.ExecuteNonQueryAsync();
//    }
//}

LOG ERROR:

2024-10-07T14:51:43.1539027-03:00 400001ca-0000-fa00-b63f-84710c7967bb [INF] Coordenadas obtidas com sucesso para localidade ID: 1 (ff4b648e)
2024-10-07T14:51:43.1555974-03:00 400001ca-0000-fa00-b63f-84710c7967bb [INF] Obter parêmetros - id:1, lat:-23.545998, lon:-46.635116 e Taskid1091 (b8f3699d)
2024-10-07T14:51:43.1569394-03:00 400001ca-0000-fa00-b63f-84710c7967bb [INF] Iniciando AtualizarCoordenadasNoBancoDeDados. (1825c0d6)
2024-10-07T14:51:43.1570229-03:00 400001ca-0000-fa00-b63f-84710c7967bb [INF] Iniciando atualização de coordenadas para localidade ID: 1 (5862d2c5)
2024-10-07T14:51:43.6551942-03:00 400001ca-0000-fa00-b63f-84710c7967bb [ERR] Erro inesperado ao atualizar coordenadas para localidade ID: 1 (f7cebc31)
System.ArgumentNullException: Value cannot be null. (Parameter 'context')
   at Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable`1 parameters)
   at Autofac.ResolutionExtensions.ResolveNamed[TService](IComponentContext context, String serviceName, IEnumerable`1 parameters)
   at Autofac.ResolutionExtensions.ResolveNamed[TService](IComponentContext context, String serviceName, Parameter[] parameters)
   at ASPNETMaker2023.Models.anima.ResolveConnection(String dbid, String name) in C:\Sistemas\Plataforma\.net\QA\anima\Models\aspnetfn.cs:line 2167
   at ASPNETMaker2023.Models.anima.GetConnection(String dbid, String name) in C:\Sistemas\Plataforma\.net\QA\anima\Models\aspnetfn.cs:line 2029
   at ASPNETMaker2023.Models.anima.GetConnectionAsync(String dbid, String name) in C:\Sistemas\Plataforma\.net\QA\anima\Models\aspnetfn.cs:line 2044
   at ASPNETMaker2023.Controllers.CoordenadasController.ExecuteStoredProcedure(String procedureName, Dictionary`2 parameters) in C:\Sistemas\Plataforma\.net\QA\anima\Controllers\apicontroller.cs:line 991
   at ASPNETMaker2023.Controllers.CoordenadasController.AtualizarCoordenadasNoBancoDeDados(Int32 idLocalidade, String lat, String lon, Int32 taskId) in C:\Sistemas\Plataforma\.net\QA\anima\Controllers\apicontroller.cs:line 968
2024-10-07T14:51:43.6574309-03:00 400001ca-0000-fa00-b63f-84710c7967bb [ERR] Erro ao atualizar coordenadas para localidade ID: 1. Erro: Value cannot be null. (Parameter 'context') (53038196)
2024-10-07T14:51:43.659012

It seemed that there is some problem in getting the database connection. How do you run the background task?

Certainly the error seems to be connection. I just don’t understand why in other parts of the controller using executoWsaync works well and when using “executeasync” or “executenonqueryasync” there is the error of connecting, I tried to use GetConnectiononasync, but it didn’t solve it either. I’m applying this code to server events, that Is it appropriate?This code should implement a background processing system to update the geographical coordinates of locations. I will explain the main aspects of how the background task should be performed:Start of the process:
The StartProcess () method is the input point. When called, he:Generates a unique ID for the task
Creates a new Taskstatus object to track progress
Obtains localities that need coordinates
Starts background processingBackground Execution:
Real processing happens within a task.run (), which performs the processing method of the asynchronous (). This allows the API to respond immediately to the customer while processing remains in the background.
Processing of locations:
Within processing coordinates, the code:Itra about each location
Assembles the full address
Get the coordinates of the API Locationiq
Updates the database with the new coordinates
Updates the status of the task regularlyCompetition Control:
Uses a Semaphoreslim to limit the number of simultaneous requests to the Geocodification API
Implements a request counting system to respect API boundaries (60 requests per minute)Error treatment and retry:
Implements an exponential backoff retry system to deal with temporary failures in the API
Registers errors and updates task status in case of problemsProgress of progress:
Maintains a Taskstatuses dictionary to track the status of each task
Offers an endpoint gettaskstatus () so that the customer can check progressCancellation:
Provides an endpoint canceltask () that allows the customer to cancel a task in progress
The code verifies periodically if the task was canceled during processingThis design allows the system to process a large number of locations efficiently without blocking the main thread of the API. The customer can start the process and then check the status or cancel the task as needed, making it suitable for long-term operations.I already thank you for any help

Not sure why the connection cannot be loaded. You may try to upgrade to ASP.NET Maker 2024 to see if the problem can be resolved.Alternatively, assuming you are using SQL Server, you can explicitly create a new database connection instead of using GetConnection. For example:

var c = new DatabaseConnection<SqlConnection, object>();

Please make sure that you cleaned up the connection after use to avoid opening too many connection.