UnitOfWork.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using DW5S.Entity;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace DW5S.Repostory
  8. {
  9. public interface IUnitOfWork : IAsyncDisposable
  10. {
  11. IRepository<TEntity, int> Of<TEntity>() where TEntity : BaseEntity<int>;
  12. IRepository<TEntity, long> OfLong<TEntity>() where TEntity : BaseEntity<long>;
  13. IRepository<TEntity,IDType> OfType<TEntity, IDType>() where TEntity : BaseEntity<IDType>;
  14. Task<int> SaveAsync();
  15. }
  16. public class UnitOfWork : IUnitOfWork
  17. {
  18. public readonly OracleContext ctx;
  19. public IRepository<TEntity, IDType> OfType<TEntity, IDType>() where TEntity : BaseEntity<IDType>
  20. {
  21. //UnitOfWork中的DbContext必须和Repository中的DbContext是同一个对象
  22. var reps = IocContainer.GetService<IRepository<TEntity, IDType>>(ctx);
  23. return reps;
  24. }
  25. public IRepository<TEntity, int> Of<TEntity>() where TEntity : BaseEntity<int>
  26. {
  27. //UnitOfWork中的DbContext必须和Repository中的DbContext是同一个对象
  28. var reps = IocContainer.GetService<IRepository<TEntity,int>>(ctx);
  29. return reps;
  30. }
  31. public IRepository<TEntity, long> OfLong<TEntity>() where TEntity : BaseEntity<long>
  32. {
  33. //UnitOfWork中的DbContext必须和Repository中的DbContext是同一个对象
  34. var reps = IocContainer.GetService<IRepository<TEntity, long>>(ctx);
  35. return reps;
  36. }
  37. public UnitOfWork(OracleContext ctx)
  38. {
  39. this.ctx = ctx;
  40. }
  41. public async Task<int> SaveAsync()
  42. {
  43. return await ctx.SaveChangesAsync();
  44. }
  45. public async ValueTask DisposeAsync()
  46. {
  47. await ctx.DisposeAsync();
  48. }
  49. }
  50. }