I have made a disposable class UnitOfWOrk which will also acts as an optional parameter, I have provided an exampel below.
public async Task CallPersistItemPassUoW()
{
using (var unitOfWork = new UnitOfWork(_connectionString, openTransaction: true))
{
try
{
await PersistItem(25, unitOfWork);
unitOfWork.Transaction.Commit();
}
catch (Exception)
{
unitOfWork.Transaction.Rollback();
}
}
}
public async Task CallPersistItem()
{
await PersistItem(30);
}
public static async Task PersistItem(int itemId, UnitOfWork ouw = null)
{
using (var unitOfWork = ouw ?? new UnitOfWork(_connectionString))
{
await unitOfWork.Connection.ExecuteScalarAsync(
"insert into [dbo].[ItemTable](ItemId) values(@ItemId)",
new
{
ItemId = itemId
},
unitOfWork.Transaction);
}
}
As you can see both the methods CallPersistItemPassUoW and CallPersistItem calls the method PersistItem. CallPersistItemPassUoW passes a used UnitOfWork while CallPersisItem doesn't pass anything. If the parameter ouw (in the method PersistItem) doesn't have a value a new instance of UnitofWork is used in the using-statment otherwise the parameter is used in the using-stamtent. This means that the same UnitOfWork instance could be used twice, is that a problem in this case? If CallPersistItemPassUoW would call PersistItem would the instance of UnitOfWork be dispoced in CallPersistItemPassUoW or in PersistItem?
Thank you!