I know using a UnitOfWork/Repository pattern in a normal class should work fine without any issues but how about using them in a static class/methods (I mean using a private static IUnitOfWork instance, refer CustomerService class). Will this work fine in multiple user scenario without overlapping with other request (I am using asp.net)?
Can anyone please tell me whether the below code looks fine or I will get any issues (overlapping db issues) going forward because of the static IUnitOfWork instance? Also, please advice me if there is any other better way to do this.
public interface IDataRepository<T> where T : class
{
IQueryable<T> Find(Expression<Func<T, bool>> predicate);
IQueryable<T> GetAll();
T GetById(Guid id);
T GetById(int id);
void Add(T entity);
void Update(T entity);
void Remove(T entity);
}
public class DataRepository<T> : IDataRepository<T> where T : class
{
}
public interface IUnitOfWork
{
IDataRepository<Customer> CustomerRepository { get; }
IDataRepository<Product> ProductRepository { get; }
void SaveChanges();
}
public class UnitOfWork : IUnitOfWork
{
private readonly SomeContext _context;
private IDataRepository<Customer> _customerRepository { get; set; }
private IDataRepository<Product> _productRepository { get; set; }
public UnitOfWork()
{
_context = new SomeContext();
}
public IDataRepository<Customer> CustomerRepository
{
get
{
if (_customerRepository == null)
{
_customerRepository = new DataRepository<Customer>(_context);
}
return _customerRepository;
}
}
public IDataRepository<Product> CustomerRepository
{
get
{
if (_productRepository == null)
{
_productRepository = new DataRepository<Product>(_context);
}
return _productRepository;
}
}
}
public class CustomerService
{
private static IUnitOfWork _unitOfWork = new UnitOfWork();
public static List<Customer> GetCustomers()
{
_unitOfWork.CustomerRepository.Find(t => t.ID == 123).ToList();
}
public static bool IsCustomerExist()
{
return (_unitOfWork.CustomerRepository.Find(t => t.ID == 123).Count() > 0);
}
public static bool UpdateCustomer(Customer customer)
{
.....
_unitOfWork.SaveChanges();
}
}