Unitofwork attribute (transaction session management for windows gui and service applications) - sharparchitecture/Sharp-Architecture-Contrib GitHub Wiki
The UnitOfWork attribute described here uses Castle Interceptors. You need to setup your application to use Contrib's Castle Windsor facilities before proceeding.
You will need to reference the following DLLs in any project that uses UnitOfWork attribute:
SharpArchContrib.Castle.dll
SharpArchContrib.Data.dll
S#arp Architecture web applications provide per-request NHibernate session management. Each web request gets a fresh NHibernate session. The UnitOfWork attribute extends the Transaction attribute to provide per-unit-of-work session management to Windows applications. If you do not use the UnitOfWork, you will have to manually manage the NHIbernate session. For example, when a transaction has to rollback, you must reset the NHibernate session to clear out invalid state.
The UnitOfWork attribute is a subclass of Transaction attribute and has all its capabilities. See the documentation page on the Transaction attribute for more information. You should use UnitOfWork in all Windows applications. If you are going to use UnitOfWork, you must also use ThreadSessionStorage as described in the documentation on how to configure your windows gui or service application and make sure that the classes/classes containing methods that use the UnitOfWork attribute are instantiated through Castle Windsor. Otherwise the attribute will not be intercepted and thus have no effect.
The following is a basic example:
[UnitOfWork]
public void DoTransaction() {
//do some work
}
UnitOfWork can be nested. For example:
[UnitOfWork]
public void DoTransaction() {
//do some work
DoInnerTransaction();
}
[UnitOfWork]
public void DoInnerTransaction() {
//do some more work
}
The transaction commits automatically if the outermost scope completes with no exceptions. The session is also closed when the outermost scope completes. If a session is closed, a new one will be opened at the start of the next NHibernate operation. The transaction rolls back if an exception occurs anywhere in the UnitOfWork. Usually, an exception that occurs during the UnitOfWork bubbles up to the caller. Throw an AbortTransactionException to force a rollback. The AbortTransactionException does not bubble up to the caller.
The UnitOfWork will cause problems with tests that use SQLLite with an in-memory database because the database structure will be lost whenever the UnitOfWork closes the NHibernate session. If you need to use SQLLite with the UnitOfWork, use a file-based database instead of the in-memory option for the SQLLite connection string.