Reputation: 1352
Working on Transactions in .net. Had a question on flowing transactions through sub functions. Do I need to use dependent transactions if the object context is common across the sub - methods?
For example, in the following code - I declare the object context in the constructor of my class (not sure if this is best practice)
public class EmployeeRepository
{
private EmployeeContext ec;
public EmployeeRepository()
{
objectContext = new EmployeeContext();
}
public InitTransaction(EmployeeEntity emp1)
{
using (TransactionScope transaction = new TransactionScope())
{
try
{ ec.employees.AddObject(emp1);
SubFunction1();
ec.SaveChanges();
}
catch
{
//catch
}
}
//commit the transaction here
ec.AcceptAllChanges();
}
public SubFunction1()
{
//some processing
//using same object context
ec.someother.AddObject(someobject);
ec.SaveChanges();
}
}
I want the subfunctions to be a part of the transactions as well? In this case should I use a dependent transaction within SubFunction1 even though I am using the same object context? Or Should I add a
using (TransactionScope transaction = new TransactionScope());
within SubFunction1. Pointers in the right direction would be greatly appreciated.
Upvotes: 1
Views: 1829
Reputation: 32437
You can consider using Dependency Injection to pass around the same ObjectContext
so you can avoid the TransactionScope
.
Instead of creating Context
inside the Repository inject it through constructor.
public class EmployeeRepository
{
private EmployeeContext ec;
public EmployeeRepository(EmployeeContext objectContext)
{
ec = objectContext;
}
}
Take a look at this answer
Upvotes: 0
Reputation: 107237
Transaction Scopes can be nested (they work similar to the SQL @@TRANCOUNT mechanism), so you could in theory use TransactionScopes in your Repository, e.g. to keep parent : child table relationships ACID, but also in your Business / Service layers as well (e.g. to have a Distributed Transaction across multiple entities, possible across multiple Databases, and even across other resources such as Message Queues and Transactional file systems.
Note that the default isolation level of TransactionScope is Read Serializable - this can lead to locking / deadlocks.
Upvotes: 1