Well in a web application a unit of work is responsible for the transaction management.
But what about a windows application?
As far as I know the repository is the connector between my data access layer and my business layer.
It hides all the data access stuff from my business layer.
Using this fact let me think of taking all the transaction stuff into the repository.
But I read that having Commit/RollBack methods on the repository is violating the repository’s intent.
I ask myself who is responsible for transaction management in a non web application and how do I hide the transaction/Nhibernate stuff from the business layer?
The general answer is “Whoever instantiates the
ISessionshould dispose of it. If the transaction has not been committed, this is effectively a rollback.”I’ve had success by using the command pattern to define an operation that I want to perform on a unit of work. Say we have a
Personentity and one of the things we can do is change a person’s name. Let’s start with the entity:Define a simple POCO Command like this:
…and a Handler for the command:
The goal is that code that exists outside of a Session/Work scope can do something like this:
The invocation of the command implies “do this command on a unit of work.” This is what we want to happen when we invoke the command:
IHandle<ChangeNameCommand>from the IoC scopeSo here’s an example using Autofac as the IoC container:
Note: The
UnitOfWorkInvokerI’ve shown here is violating SRP – it is aUnitOfWorkFactory, aUnitOfWork, and anInvokerall in one. In my actual implementation, I broke them out.