I am looking at the official documentation of Xamarin and they seem to encourage using statics/singleton for a Database Connection, which seems weird to me:
This approach creates a single database connection that is kept open while the application runs, therefore avoiding the expense of opening and closing the database file each time a database operation is performed. static TodoItemDatabase database;
public static TodoItemDatabase Database
{
get
{
if (database == null)
{
database = new TodoItemDatabase(DependencyService.Get<IFileHelper>().GetLocalFilePath("TodoSQLite.db3"));
}
return database;
}
}
Singleton – The Singleton pattern provides for a way in which only a single instance of a particular object can ever exist. For example, when using SQLite in mobile applications, you only ever want one instance of the database. Using the Singleton pattern is a simple way to ensure this.
The TaskItemDatabase is a singleton, ensuring that all access occurs against the same instance. A lock is used to prevent concurrent access from multiple threads.
public T GetItem<T> (int id) where T : BL.Contracts.IBusinessEntity, new ()
{
lock (locker) {
return Table<T>().FirstOrDefault(x => x.ID == id);
}
}
It seems to me though that this is a widely discouraged idea in general, for instance here on SO: getting db connection through singleton class Is singleton approach right for accessing/maintaining database and internet connection
So, any idea why does Xamarin team promote this approach? Is it different because of some particularity of their framework? And more importantly, if not that, then what is the proper approach?