So using the UnitOfWork pattern in MVC I don't want to have to call unitOfWork save method every time I modify an object. Usually with UnitOfWork you do something like this:
if (ModelState.IsValid)
{
var user = new User()
{
Id = Guid.NewGuid(),
Username = model.Username,
Email = model.Email,
Password = model.HashedPassword()
};
unitOfWork.UserRepository.Insert(user);
unitOfWork.Save();
}
I'd like to remove the "unitOfWork.Save();" line and just know that it will save every time an action completes. So I added a save clause to the Dispose method of my UnitOfWork:
protected virtual void Dispose(bool disposing)
{
if (context.ChangeTracker.HasChanges())
{
context.SaveChangesAsync();
}
if (!this.isDisposed)
{
if (disposing)
{
context.Dispose();
}
}
this.isDisposed = true;
}
And of course my controller calls the dispose:
protected override void Dispose(bool disposing)
{
unitOfWork.Dispose();
base.Dispose(disposing);
}
I'm confident that the HasChanges() method works as expected and SaveChangesAsync() is called, yet this doesn't work. I'm thinking that it could be something to do with the thread created by SaveChangesAsync not completing because it the object it depends on is disposed?
But if that's the case then SaveChangesAsync must be dangerous, because even if you used it in the controller action it could get transaction locked for a few seconds and find that the context has been disposed before it gets a chance to save.
So what am I doing wrong? I can't seem to find an established way of doing this, yet I can't imagine that everyone who uses the unit of work pattern has to remember to manually call the Save method every time they modify any objects.