lundi 29 juin 2015

Using statement or GC to dispose of a connection

I'm using a pattern where I constructor inject an IDbConnection instance into my class which is then assigned to a local variable before being used with Dapper to populate a List with objects from a database.

I understand that best practice is to wrap the connection object in a using statement, however when I try and reuse the connection to reload objects, I cannot because the connection has already been disposed. Would it be ok for me to just open and close the connection in the LoadValues method, and trust the class destructor to dispose of my object instead of having a using statement? Perhaps there's a better way that I've not considered?

Here is my class:

Public Class AmountLookup : Implements INAmountLookup
    Private _listOfRecords As New List(Of NAmount)
    Private ReadOnly _mfConnection As IDbConnection
    Private ReadOnly _fRepository As IFRepository

    Sub New(mfConnection As IDbConnection,
            fRepository As IFRepository)
        _mfConnection = mfConnection
        _fRepository = fRepository
        LoadValues()
    End Sub

    Public Sub LoadValues() Implements INAmountLookup.LoadValues
        LoadValues(DateGateway.GetLastWorkingDayOfPreviousMonth)
    End Sub

    Public Sub LoadValues(currentNDate As Date) Implements INAmountLookup.LoadValues
        _listOfRecords.Clear()

        Dim sql = String.Format(SqlFactory.GetSql(DBC.SQLs.ValidatedNAmounts),
                                _fRepository.GetFormattedListOfFsForSqlSearch,
                                Format(currentNDate, DBC.DateFormats.MfDate))

        Using _mfConnection
            _mfConnection.Open()
            _listOfRecords = _mfConnection.Query(Of NAmount)(sql).ToList
            _mfConnection.Close()
        End Using
    End Sub

    Public Function Find(fCodeValue As String) As NAmount Implements INAmountLookup.Find
        Dim myList = _listOfRecords.Where(Function(x) x.FCode = fCodeValue)
        Return myList.SingleOrDefault()
    End Function
End Class

Aucun commentaire:

Enregistrer un commentaire