From 66055f1d7c42ac4a285b33c3770ce0559aaac34d Mon Sep 17 00:00:00 2001 From: Kyle Spearrin Date: Tue, 2 Jun 2020 09:13:57 -0400 Subject: [PATCH] Singleton LiteDatabase (#946) * update litedb. initialize db as a static singleton instance. * dont need to dispose anymore --- src/Core/Core.csproj | 2 +- src/Core/Services/LiteDbStorageService.cs | 20 +++++++++++--------- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/src/Core/Core.csproj b/src/Core/Core.csproj index 729d4e82d..923688580 100644 --- a/src/Core/Core.csproj +++ b/src/Core/Core.csproj @@ -24,7 +24,7 @@ - + diff --git a/src/Core/Services/LiteDbStorageService.cs b/src/Core/Services/LiteDbStorageService.cs index 7ba9617f5..9fcdcb3a7 100644 --- a/src/Core/Services/LiteDbStorageService.cs +++ b/src/Core/Services/LiteDbStorageService.cs @@ -2,14 +2,16 @@ using LiteDB; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; -using System; using System.Linq; using System.Threading.Tasks; namespace Bit.Core.Services { - public class LiteDbStorageService : IStorageService, IDisposable + public class LiteDbStorageService : IStorageService { + private static LiteDatabase _db; + private static readonly object _lock = new object(); + private readonly JsonSerializerSettings _jsonSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() @@ -17,7 +19,6 @@ namespace Bit.Core.Services private readonly string _dbPath; private ILiteCollection _collection; private Task _initTask; - private LiteDatabase _db; public LiteDbStorageService(string dbPath) { @@ -38,7 +39,13 @@ namespace Bit.Core.Services { try { - _db = new LiteDatabase($"Filename={_dbPath};Upgrade=true;"); + lock (_lock) + { + if (_db == null) + { + _db = new LiteDatabase($"Filename={_dbPath};Upgrade=true;"); + } + } _collection = _db.GetCollection("json_items"); } finally @@ -73,11 +80,6 @@ namespace Bit.Core.Services _collection.DeleteMany(i => i.Id == key); } - public void Dispose() - { - _db?.Dispose(); - } - private class JsonItem { public JsonItem() { }