Search code examples
c#.net.net-6.0unit-of-worksavechanges

Using UnitOfWork design at different endpoints. Can't tracking entity updates when I try to apply savechanges. #.net (UnitOfWork design)


If I use the two service's method at same action like below It is working.

 [HttpPost, Route("save_changes")]
    public async Task<IActionResult> SaveChangesAsync()
    {
        _logService.CreateLog(logCreateModel);
        await _unitOfWork.SaveChangesAsync();
        return Ok();
    }

But I need to call the entity updating and SaveChanges methods at different action Because I want to send request from different API.Like this;

[HttpPost, Route("create")]
    public async Task CreateLog(LogCreateModel logCreateModel)
    {
        await _logService.CreateLog(logCreateModel);
    }

 [HttpPost, Route("save_changes")]
    public async Task<IActionResult> SaveChangesAsync()
    {
        unitOfWork.SaveChangesAsync();
        return Ok();
    }

and this my UnitOfWork class;

public class UnitOfWork : IUnitOfWork
{
    private readonly PrimeLogDatabaseContext _context;
       
    private IRepository<Log> _log;
    private IRepository<LifeCycle> _lifeCycle;

    public UnitOfWork(PrimeLogDatabaseContext context)
    {
        _context = context;
    }
  
    public IRepository<Log> log => _log ?? new LogRepository(_context);
    public IRepository<LifeCycle> lifeCycle => _lifeCycle ?? new LifeCycleRepository(_context);

    public async Task SaveChangesAsync()
    {
     await _context.SaveChangesAsync();
    }

    public void SaveChanges()
    {
        _context.SaveChanges();
    }
}

How I can?

P.s: I want to create more than one log and at the end of the request I want commit all logs to database. I used the UnitOfWork design because I have to seperate SaveChanges method from creation process. At Another API I have action which including CreateLog request services. And I send request to SaveChanges with using the attribute that trigger when action result.


Solution

  • After months ; I solved this problem with another design pattern. I used to UnitOfWork structure at one Api(working as middleware one) and used chain of responsibility pattern.

    For more information(18.05.2023);

    If you want to act when savechanges stage you should use UnitOfWork pattern structure. But in this issue different by some reasons (I need different actions for different saving actions). The usable pattern was chain of responsibility because processes are follow each other. You should attribute for service classes that include save actions. This attribute reach UnitOfWork service or directly save method by Attribute param. But applying different methods for different actions is not proper for SOLID and when you request to this endpoint effect timeout errors. So we have just one good case; you should build Generic service structure begin of the project.