Reza Shirazi
Reza Shirazi

Reputation: 381

Dapper SqlConnection becomes null or closed after ExecuteAsync

I am using Dapper in an ASP.NET Core 6 Web API application. I used DI to inject SqlConnection and begin a transaction, as shown below. Then in one of my services, I use the UnitOfWork to make to inserts into two different tables.

The first insert is OK but for the second one both of my _sqlConnection and _dbTransaction variables become null. I have no idea how this is happening. Could you help, please.

Startup.cs

services.AddScoped((s) => new SqlConnection(Configuration["APPSETTINGS_SQL_CONNECTION_STRING"]));

services.AddScoped<IDbTransaction>((s) =>
            {
                var connection = s.GetRequiredService<SqlConnection>();
                var tokenService = s.GetRequiredService<ITokenService>();
                connection.AccessToken = tokenService.GetAccessToken();
                connection.Open();
                return connection.BeginTransaction();
            });
services.AddTransient<ITokenService, TokenService>();
services.AddTransient<IUnitOfWork, UnitOfWork>();

RepositoryBase.cs:

public RepositoryBase(IDbTransaction dbTransaction, SqlConnection sqlConnection)
{
    _dbTransaction = dbTransaction;
    _sqlConnection = sqlConnection;         
}
    
private async Task<int> CreateEntity(T entity, string sql)
{
    return await _sqlConnection.ExecuteAsync(sql, transaction: _dbTransaction);
}

Service.cs:

var workerMappingTask = _unitOfWork.MappingRepository.CreateAsync(
                        WorkerMappingEntity.Create(1,"test","12"));
    
var workerConsentTask = _unitOfWork.WorkerRepository.CreateAsync(100,"test","123","123"));
    
await Task.WhenAll(new Task[] { workerMappingTask, workerConsentTask });

_unitOfWork.Commit();

Upvotes: 0

Views: 407

Answers (0)

Related Questions