Асинхронные запросы к бд Dapper - Web Api

132
03 декабря 2019, 08:10

Есть связка Angular 7 + Web Api 2 с архитектурой N-Tier, для запроса к бд использую Dapper При отправке асинхронных запросов с Angular получаю разные ошибки:

1) Unable to cast object of type 'System.Data.ProviderBase.DbConnectionClosedConnecting' to type 'System.Data.SqlClient.SqlInternalConnectionTds 2) BeginExecuteReader requires an open and available Connection. The connection's current state is connecting. 3) Invalid operation. The connection is closed

Код из репозитория.

public async Task<IEnumerable<TournamentEntity>> GetActiveTournamentsAsync()
    {
        var tournaments = await Db.QueryAsync<TournamentEntity>("GetActiveTournaments", commandType: CommandType.StoredProcedure);
        return tournaments;
    }
    public async Task<IEnumerable<TournamentEntity>> GetAllAsync()
    {
        var tournaments = await Db.QueryAsync<TournamentEntity>("GetAllTournaments", commandType: CommandType.StoredProcedure);
        return tournaments;
    }
    public async Task<IEnumerable<string>> GetAllTournamentsTypesAsync()
    {
        var types = await Db.QueryAsync<string>("GetAllTournamentsTypes", commandType: CommandType.StoredProcedure);
        return types;
    }

Регистрация в контейнере DependencyInjection (Встроенный в WebApi)

    var connectionString = configuration.GetConnectionString("AmatorConnection");
        services.AddSingleton<IDbConnection>(new SqlConnection(connectionString));
services.AddScoped<ITournamentRepository, TournamentRepository>();

Конструктор репозитория

public TournamentRepository(IDbConnection dbConnection, ILogger<TournamentRepository> logger) : base(dbConnection)
    {
        Db = dbConnection;
        _logger = logger;
    }

Интерфейс репозитория

public interface ITournamentRepository : IBaseRepository<TournamentEntity>
{
    Task<IEnumerable<TournamentEntity>> GetActiveTournamentsAsync();
    Task<IEnumerable<string>> GetAllTournamentsTypesAsync();
    Task<IEnumerable<TournamentEntity>> GetChildTournamentsAsync(int? tournamentId);
}

Вызов конструктора на уровне бизнес логики

public async Task<IEnumerable<TournamentResource>> GetActiveTournamentsAsync()
    {
        var tournamentEntities = await _tournamentRepository.GetActiveTournamentsAsync();
        return _mapper.Map<IEnumerable<TournamentResource>>(tournamentEntities);
    }
    public async Task<IEnumerable<string>> GetAllTournamentTypesAsync()
    {
        var types = await _tournamentRepository.GetAllTournamentsTypesAsync();
        return types;
    }

Вызов сервисов на уровне контроллеров

[HttpGet]
    [AllowAnonymous]
    [Route("active")]
    public async Task<IActionResult> GetActiveTournamentsAsync()
    {
        try
        {
            var activeTournaments = await _tournamentService.GetActiveTournamentsAsync();
            return Ok(activeTournaments);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex.Message);
            return BadRequest("Не удалось получить список активных турниров");
        }
    }
    [HttpGet]
    [AllowAnonymous]
    [Route("types")]
    public async Task<IActionResult> GetAllTournamentTypesAsync()
    {
        try
        {
            var types = await _tournamentService.GetAllTournamentTypesAsync();
            return Ok(types);
        }
        catch(Exception ex)
        {
            _logger.LogError(ex.Message);
            return BadRequest("Не удалось получить список групп турниров");
        }
    }
Answer 1

Если кому-то поможет в будущем, то я решил этот вопрос так:

Из-за того, что IDbConnection был Singleton, то он не мог разорваться на несколько запросов.

Пришлось при каждом запросе к бд создавать новую сущность IDbConnection обернув её в конструкцию using

using (var connection = new IDbConnection("...."))
{DoStuff...}
READ ALSO
Фоновые службы в Unity

Фоновые службы в Unity

Сейчас появилась потребность в реализации следующего: знать сколько именно отсутствовал пользователь в приложении и в зависимости от этого...

156
Взаимодействие двух форм через событие. WinForms

Взаимодействие двух форм через событие. WinForms

Здравствуйте! Подскажите как создать событие, чтоб оповестить главную форму о том, что в Form2 что-то произошло?

126
Проблема с запуском игры на Unity 5

Проблема с запуском игры на Unity 5

Дело в том что настройки игры, а именно момент когда я хочу сохранить значения PlayerPrefs, и в тестировочном режиме запустить свои наработки, происходит...

113
Как сделать остановку персонажа Unity3D?

Как сделать остановку персонажа Unity3D?

Проект 2DПерсонаж двигается вверх и вниз

117