110 lines
3.1 KiB
C#
110 lines
3.1 KiB
C#
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
|
|
{
|
|
/// <summary>
|
|
/// Service welcher Operationen in einem Repository gruppiert und bestätigt (speichert).
|
|
/// Weiters werden die einzelnen Repositories nur über diesen Service abgerufen
|
|
/// </summary>
|
|
public class UnitOfWork : IUnitOfWork
|
|
{
|
|
private readonly LocalDbContext _context;
|
|
private bool _disposed = false;
|
|
private readonly Dictionary<object, object> _repositories = new Dictionary<object, object>();
|
|
private readonly AsyncLock _asyncLock;
|
|
|
|
/// <summary>
|
|
/// Erstellt eine Instanz
|
|
/// </summary>
|
|
/// <param name="context">Datenbank-Kontext</param>
|
|
public UnitOfWork(LocalDbContext context)
|
|
{
|
|
_asyncLock = new AsyncLock();
|
|
_context = context;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gibt ein Repository im Kontext der UnitOfWork zurück
|
|
/// </summary>
|
|
/// <typeparam name="T">Typ (Klasse)</typeparam>
|
|
/// <returns>IRepository oder null, wenn nicht verfügbar</returns>
|
|
public IRepository<T> GetRepository<T>() where T : class
|
|
{
|
|
if (!_repositories.ContainsKey(typeof(T)))
|
|
{
|
|
_repositories.Add(typeof(T), new Repository<T>(_context as DbContext, _asyncLock));
|
|
}
|
|
return (IRepository<T>)_repositories[typeof(T)];
|
|
}
|
|
|
|
/// <summary>
|
|
/// Schließt Daten-Änderungen ab und speichert die selben
|
|
/// </summary>
|
|
public int Commit()
|
|
{
|
|
using (_asyncLock.Lock())
|
|
{
|
|
try
|
|
{
|
|
return _context.SaveChanges();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
System.Diagnostics.Debug.WriteLine(ex.Message);
|
|
return 0;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Schließt Daten-Änderungen ab und speichert die selben
|
|
/// </summary>
|
|
public async Task<int> CommitAsync()
|
|
{
|
|
using (await _asyncLock.LockAsync())
|
|
{
|
|
try
|
|
{
|
|
return await _context.SaveChangesAsync();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
System.Diagnostics.Debug.WriteLine(ex.Message);
|
|
return 0;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Dispose
|
|
/// </summary>
|
|
/// <param name="disposing"></param>
|
|
protected virtual void Dispose(bool disposing)
|
|
{
|
|
if (!this._disposed)
|
|
{
|
|
if (disposing)
|
|
{
|
|
_context.Dispose();
|
|
}
|
|
}
|
|
this._disposed = true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Dispose
|
|
/// </summary>
|
|
public void Dispose()
|
|
{
|
|
Dispose(true);
|
|
GC.SuppressFinalize(this);
|
|
}
|
|
}
|
|
}
|