You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

50 lines
1.3 KiB

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TaskManager.Entity;
using TaskManager.EntityFramework;
namespace TaskManager.EntityFramework.Repository
{
public interface ITaskUnitOfWork : IDisposable
{
IRepository<TEntity> GetRepository<TEntity>() where TEntity : BaseEntity;
Task<int> SaveChangesAsync();
}
public class TaskUnitOfWork : ITaskUnitOfWork
{
private readonly DbContext _context;
private readonly Dictionary<Type, object> _repositories = new();
public TaskUnitOfWork(DbContext context)
{
_context = context;
}
public IRepository<TEntity> GetRepository<TEntity>() where TEntity : BaseEntity
{
if (_repositories.TryGetValue(typeof(TEntity), out var repo))
{
return (IRepository<TEntity>)repo;
}
var newRepo = new Repository<TEntity>(_context);
_repositories[typeof(TEntity)] = newRepo;
return newRepo;
}
public async Task<int> SaveChangesAsync()
{
return await _context.SaveChangesAsync();
}
public void Dispose()
{
_context.Dispose();
}
}
}