/// <summary> /// Ensure that database connection opened. If opened connection missing, it will be opened asynchronously. /// </summary> /// <param name="cancellationToken">Asynchronous operation cancellation token.</param> /// <returns>Async operation task.</returns> public async Task EnsureConnectionAsync(CancellationToken cancellationToken = default) { if (_connection == null) { IDbConnection connection; if (_connectionFactory != null) { connection = _connectionFactory(); } else { connection = DataProvider.CreateConnection(ConnectionString); } _connection = AsyncFactory.Create(connection); if (RetryPolicy != null) { _connection = new RetryingDbConnection(this, _connection, RetryPolicy); } } if (_connection.State == ConnectionState.Closed) { try { var task = OnBeforeConnectionOpenAsync?.Invoke(this, _connection.Connection, cancellationToken); if (task != null) { await task; } await _connection.OpenAsync(cancellationToken); _closeConnection = true; task = OnConnectionOpenedAsync?.Invoke(this, _connection.Connection, cancellationToken); if (task != null) { await task; } } catch (Exception ex) { if (TraceSwitch.TraceError) { OnTraceConnection(new TraceInfo(TraceInfoStep.Error) { TraceLevel = TraceLevel.Error, DataConnection = this, StartTime = DateTime.UtcNow, Exception = ex, IsAsync = true, }); } throw; } } }
/// <summary> /// Ensure that database connection opened. If opened connection missing, it will be opened asynchronously. /// </summary> /// <param name="cancellationToken">Asynchronous operation cancellation token.</param> /// <returns>Async operation task.</returns> public async Task EnsureConnectionAsync(CancellationToken cancellationToken = default) { CheckAndThrowOnDisposed(); if (_connection == null) { IDbConnection connection; if (_connectionFactory != null) { connection = _connectionFactory(); } else { connection = DataProvider.CreateConnection(ConnectionString !); } _connection = AsyncFactory.Create(connection); if (RetryPolicy != null) { _connection = new RetryingDbConnection(this, _connection, RetryPolicy); } } if (_connection.State == ConnectionState.Closed) { try { var task = OnBeforeConnectionOpenAsync?.Invoke(this, _connection.Connection, cancellationToken); if (task != null) { await task.ConfigureAwait(Common.Configuration.ContinueOnCapturedContext); } await _connection.OpenAsync(cancellationToken).ConfigureAwait(Common.Configuration.ContinueOnCapturedContext); _closeConnection = true; task = OnConnectionOpenedAsync?.Invoke(this, _connection.Connection, cancellationToken); if (task != null) { await task.ConfigureAwait(Common.Configuration.ContinueOnCapturedContext); } } catch (Exception ex) { if (TraceSwitchConnection.TraceError) { OnTraceConnection(new TraceInfo(this, TraceInfoStep.Error, TraceOperation.Open, true) { TraceLevel = TraceLevel.Error, StartTime = DateTime.UtcNow, Exception = ex, }); } throw; } } }