UnitOfWork.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. /// <summary>
  15. /// 保存
  16. /// </summary>
  17. /// <param name="changedEntityTypes">变化的模型,用于清空模型对应的缓存</param>
  18. /// <returns></returns>
  19. Task<int> SaveAsync(params Type[] changedEntityTypes);
  20. }
  21. public class UnitOfWork : IUnitOfWork
  22. {
  23. public readonly OracleContext ctx;
  24. public IRepository<TEntity, IDType> OfType<TEntity, IDType>() where TEntity : BaseEntity<IDType>
  25. {
  26. //UnitOfWork中的DbContext必须和Repository中的DbContext是同一个对象
  27. var reps = IocContainer.GetService<IRepository<TEntity, IDType>>(ctx);
  28. return reps;
  29. }
  30. public IRepository<TEntity, int> Of<TEntity>() where TEntity : BaseEntity<int>
  31. {
  32. //UnitOfWork中的DbContext必须和Repository中的DbContext是同一个对象
  33. var reps = IocContainer.GetService<IRepository<TEntity,int>>(ctx);
  34. return reps;
  35. }
  36. public IRepository<TEntity, long> OfLong<TEntity>() where TEntity : BaseEntity<long>
  37. {
  38. //UnitOfWork中的DbContext必须和Repository中的DbContext是同一个对象
  39. var reps = IocContainer.GetService<IRepository<TEntity, long>>(ctx);
  40. return reps;
  41. }
  42. public UnitOfWork(OracleContext ctx)
  43. {
  44. this.ctx = ctx;
  45. }
  46. public async Task<int> SaveAsync(params Type[] changedEntityTypes)
  47. {
  48. if (changedEntityTypes != null)
  49. {
  50. if (changedEntityTypes.Contains(typeof(XlInfo)))
  51. {
  52. IocContainer.Cache.Remove(CacheKeys.AllXlSat);
  53. }
  54. else if (changedEntityTypes.Contains(typeof(SatInfo)))
  55. {
  56. IocContainer.Cache.Remove(CacheKeys.AllSat);
  57. }
  58. }
  59. return await ctx.SaveChangesAsync();
  60. }
  61. public async ValueTask DisposeAsync()
  62. {
  63. await ctx.DisposeAsync();
  64. }
  65. }
  66. }