Question

I would like to know if the MvvmCross container can handle the disposal of the SQLite connection or should this be done manually in the repository.

I have seen code examples like the following that don't manually dispose or close the SQLite connection:

public class ExampleRepository
{
    private readonly ISQLiteConnection _connection;

    public ExampleRepository(ISQLiteConnectionFactory factory)
    {
        _connection = factory.Create("Example.db");
        _connection.CreateTable<Example>();
    }

    public IEnumerable<Example> All()
    {
        return _connection.Table<Example>().ToList();
    }
}

Would this be a better option?

public class ExampleRepository
{
    private readonly ISQLiteConnectionFactory _factory;

    public ExampleRepository(ISQLiteConnectionFactory factory)
    {
        _factory = factory;
    }

    public IEnumerable<Example> All()
    {
        using (var connection = _factory.Create("Example.db"))
        {
            connection.CreateTable<Example>();
            return connection.Table<Example>().ToList();
        }
    }
}

Would it be better to use a using block to dispose of the connection each time it is used in the the repository?

Or is it more overhead to keep creating and disposing the connection. Hence the reason for leaving it open in the first example?

Was it helpful?

Solution

When in instantiate any IDisposable object, you can do so with a using statement. Any time the execution returns from the scope of a using, the object will be disposed. This includes returns and exceptions.

using (var obj = new Connection()) {
    throw new Exception("This will dispose of obj");
}

When you build a class that needs a persistent IDisposable object like yours, you should also make your own class IDisposable, and dispose of those objects in the Dispose() method:

public class MyClass : IDisposable
{
    Connection con = new Connection();
    public void Dispose()
    {
        con.Dispose();
    }
}

Then when you instantiate your own class, use using, and everything will be happily disposed of when appropriate.

using (var obj = new MyClass()) {
    throw new Exception("This will dispose of obj, and obj.con");
}

Ultimately, the later solution is best, because:

  • you create resources when necessary
  • reuse them efficiently
  • and dispose of them properly

OTHER TIPS

Would it be better to use a using block to dispose of the connection each time it is used in the the repository?

YES it is always good to use using{} block(for the classes which implemet IDisposable interface) as it will make sure that object willbe disposed once it leaves the block.

using (var connection = _factory.Create("Example.db"))
    {
        connection.CreateTable<Example>();
        return connection.Table<Example>().ToList();
    }//dispose here
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top