Keep LiteDB open for the entire program lifecycle?
12:11 29 Mar 2023

For situations where a model or viewmodel retrieves needed data (different threads?), is it possible to make a singleton, open db on program start, keep it open the entire time, only closing on program termination? Can this be used in production?

class ThumbsDb
{
    private LiteDatabase db;
    private ILiteCollection col;
    private static readonly Lazy lazy = new Lazy(() => new ThumbsDb());
    public static ThumbsDb Instance
    {
        get { return lazy.Value; }
    }
    public ThumbsDb()
    {
        db = new LiteDatabase(new ConnectionString
        {
            Filename = SettingsManager.GetThumbsDbFullPath(),
            Connection = ConnectionType.Direct
        });
        col = db.GetCollection("Thumbs");
    }
    
    public void StoreThumb(string fullpath, BitmapSource bitmap)
    {   
        col.EnsureIndex(x => x.Path, unique: true);

        Thumb t = new Thumb()
        {           
            Img = (BitmapSource)bitmap          
        };
        col.Upsert(fullpath, Thumb);
    }
    public BitmapSource RetrieveThumb(string fullpath)
    {
        Thumb t = col.FindOne(x => x.Path.Equals(fullpath));
        return t.Img;
    }
litedb