using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using gehGassiApp.Core.Data; namespace gehGassiApp.Data { /// /// Service welcher Operationen in einem Repository gruppiert und bestätigt (speichert). /// Weiters werden die einzelnen Repositories nur über diesen Service abgerufen /// public class UnitOfWork : IUnitOfWork { private readonly LocalDbContext _context; private bool _disposed = false; private readonly Dictionary _repositories = new Dictionary(); private readonly AsyncLock _asyncLock; /// /// Erstellt eine Instanz /// /// Datenbank-Kontext public UnitOfWork(LocalDbContext context) { _asyncLock = new AsyncLock(); _context = context; } /// /// Gibt ein Repository im Kontext der UnitOfWork zurück /// /// Typ (Klasse) /// IRepository oder null, wenn nicht verfügbar public IRepository GetRepository() where T : class { if (!_repositories.ContainsKey(typeof(T))) { _repositories.Add(typeof(T), new Repository(_context as DbContext, _asyncLock)); } return (IRepository)_repositories[typeof(T)]; } /// /// Schließt Daten-Änderungen ab und speichert die selben /// public int Commit() { using (_asyncLock.Lock()) { try { return _context.SaveChanges(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); return 0; } } } /// /// Schließt Daten-Änderungen ab und speichert die selben /// public async Task CommitAsync() { using (await _asyncLock.LockAsync()) { try { return await _context.SaveChangesAsync(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); return 0; } } } /// /// Dispose /// /// protected virtual void Dispose(bool disposing) { if (!this._disposed) { if (disposing) { _context.Dispose(); } } this._disposed = true; } /// /// Dispose /// public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } }