How do I encapsulate the saving of more than one entity in a transactional manner using the repository pattern? For example, what if I wanted to add an order and update the
Using Spring.NET AOP + NHibernate you can write your repository class as normal and configure your transactions in custom XML file:
public class CustomerService : ICustomerService
{
private readonly ICustomerRepository _customerRepository;
private readonly IOrderRepository _orderRepository;
public CustomerService(
ICustomerRepository customerRepository,
IOrderRepository orderRepository)
{
_customerRepository = customerRepository;
_orderRepository = orderRepository;
}
public int CreateOrder(Order o, Customer c)
{
// Do something with _customerRepository and _orderRepository
}
}
In the XML file you select which methods you would like to be executed inside a transaction:
And in your code you obtain an instance of the CustomerService class like this:
ICustomerService customerService = (ICustomerService)ContextRegistry
.GetContent()
.GetObject("customerService");
Spring.NET will return you a proxy of the CustomerService class that will apply a transaction when you call CreateOrder method. This way there's no transaction specific code inside your service classes. AOP takes care of it. For more details you can take a look at the documentation of Spring.NET.