This is the first sample in a series of blogs about NHibernate in ASP.Net environment. This version gives a user new to NHibernate the absolute minimum pieces to start a well architected application. A number of the pieces necessary for an enterprise-capable application are not yet included, but the foundation has been laid. Source code and starter solution described in this post are available at NHibernateBootstrap Download.
The key pieces in this sample are demonstrations of the correct UnitOfWork pattern, using the NHibernate ISession based object with its transaction support. A DataAccessObject / Repository is also introduced that uses features from both styles of implementations and is also intended to work with Query Objects. The Web.Config file includes a starter configuration for NHibernate, using the LinFu proxy. The connection between the web application and NHibernate demonstrates a best practice, where the Session Per Request pattern is initialized in an IHttpModule - RequestHttpModule.cs. This is an implementation base on the ManagedWebSessionContext, and shows how to bind and unbind the session correctly.
This web application sample is not a best practices sample for ASP.Net development, but future blogs will add features, especially where they take advantage of an NHibernate implementation. Some of the implementation of the Person page is not following normal Microsoft recommended methods, and appear to be more complex than necessary. These changes are part of a further foundation and will allow the page to be transformed later where more than 95% of the logic normally encapsulated in the page behind code becomes testable. Initially there will be some references to NHibernate in the Web Application project, but this is not a recommended practice - later modifications will move these references so that they are in the BusinessServices project.
The one other item included in this sample is the Unit Test project. This test project connects to NHibernate using the ThreadStaticSessionContext. Each Test Fixture initializes its own ISession object and uses the same session object for all tests in that fixture. The app.config file for the test project, which configures the NHibernate support, is located in the bin/debug directory.
The Bootstrapper uses a multi-project structure and a library at the solution level to hold all the files:
NHibernate Bootstrap Solution
SharedLibs - a folder containing all external reference dll's and associated files
BootstrapperUnitTests Project - holds unit tests
Infrastructure Project - holds high level Interface and class files that may be used in multiple projects in the solution
DomainModel Project - holds the object model for the solution
NHibernateDAO Project - the persistence layer, gets data into and out of the database based on the object model and holds the mapping files
DataServices Project - isolates the persistence layer from the rest of the application
BusinessServices Project - provides an integration of the business logic with the data and controls the flow of information to and from the presentation layer
WebNHibernate Project - provides a web based presentation layer
Jason Dentler has written a series of blogs about using NHibernate, and I am borrowing from his discussion on DAOs, Repositories or Query Objects. The basic setup of the persistence layer uses a DAO-type FindBy approach augmented with support for QueryObjects. It is not my intent to discuss this approach now, but to cover it in a later post.
The purpose of this post is to discuss the ISession object and how to use it directly as a UnitOfWork, without an additional wrapper. The second purpose is to present a recommended solution for the SessionPerRequest architecture for an ASP.Net application.
The SessionPerRequest implementation is recommended as a best practice to ensure that NHibernate is the most responsive and utilizes the least possible resources in the Web Server environment. The NHibernate.Context.ICurrentSessionContext is discussed in the reference document: NHibernate - Relational Persistence for Idiomatic .NET. The appropriate choices for a web application are either ManagedWebSessionContext or the WebSessionContext. (@Fabio: Can you explain the difference between the 2 - I have reviewed the code and see that ManagedWebSessionContext supports a GetExistingSession() - Does the WebSessionContext need to be explicitly bound and unbound in each request?)
Numerous examples of using ManagedWebSessionContext use the Global.asax to connect the NHibernate context to the web server. This is a bad practice in that it means the web application must have a direct reference to NHibernate.Context in order to work. It is instead recommended that an IHttpModule be created, and that the binding module be in the same project where the NHibernate reference is - in this sample that would be the NHibernateDOA project. This serves to isolate NHibernate from the web application entirely. All that is required is that the web application bin directory have a copy of the NHibernate dlls.
The code for the IHttpModule is shown below:
The use of the ManagedWebSessionContext is fairly straight forward. It is important to note that this file has a reference to System.Web, which should be the only reference to this library outside of the the WebApplication itself. It is undesirable to reference the System.Web library external to the web application project as it will make testing of those components with that reference very difficult.
The context_EndRequest also contains a Rollback call, which will ensure that any pending transactions are terminated without writing to the database if your application has an unhandled error.
In order for the custom IHttpModule to be active in the web server it must be registered in the Web.Config file:
I have included the IHttpModule reference twice. The first time is for configurations of the web server using Classic Mode and the second is for IIS 7 Integrated Pipeline. See http://msdn.microsoft.com/en-us/library/ms227673.aspx
The final item necessary to make this work is an addition to the NHibernate configuration file. It is necessary to add the property
This is shown below in the Web.Config described in the Minimal Configuration section.
The proper management of database connections is a key component of ensuring a highly responsive web application in ASP.Net. http://nhforge.org/doc/nh/en/index.html#transactions gives some guidance, but does not provide any code samples or say what the recommended practice should be. This lack of direction is partly due to the possible scope of applications for NHibernate in general. However, in an ASP.Net environment the rules are fairly simple. First, you should SessionPerRequest as detailed above. Second, all database access should be wrapped in a transaction and that transaction should be committed when the connection to the database can be released. There is an almost infinite variation of implementations for these requirements in samples on the Internet. Invariably, programmers try to encapsulate the ISession object and transaction in a UnitOfWork class. While many of these samples are not incorrect in there implementation, some are, and many do not provide any additional functionality or save lines of code, when compared to a proper implementation of the bare ISession object.
First some sample GenericDAO code (again, thanks to Jason Dentler, who provided the basic pattern). The declaration for the class:
A DAO implementation for NHibernate will usually have a GetByID, and this is no exception:
The less normal GetBy query mechanism, is more normally part of a repository architecture, but makes for some very flexible code here:
The Save function is the last part of the GenericDAOImpl class (note that there is no Delete function, as this capability is only exposed in the specific DAO classes actually requiring that function, rather than as a generic capability):
Each method in the GenericDAO class has 2 paths: one where the caller has wrapped the call in a transaction, and the other where no transaction was specified in the call. (Note: It is not necessary to check m_session.Transaction != null as the transaction will never be null if the ISession instance is valid, and the ISession instance must be valid to use the GenericDAO implementation.) It is left as an exercise for the reader to build a function to query using HQL.
An example test is shown below, first without an explicit transaction and then with a transaction:
Now with a transaction included in the test method:
There are 2 additional lines of code in the sample with a direct call to the transaction. Any other UnitOfWork implementation cannot improve on this and still work correctly.
NHibernate needs a program to read the configuration and initialize the SessionFactory. This is called the SessionManager.cs is shown below the configuration and unit test setup code.
The web.config file holds the configuration details as shown below:
The Unit Test project has a similar configuration, but it is stored in an app.config file in the bin directory with some minor changes. The show_sql property is set to true, causing the sql to be output in the NUnit console display. The second change is that the property current_session_context_class is set to ThreadStaticSessionContext. In this case the current context needs it own setup:
I waited to show the SessionManager.cs code, as it was necessary to understand how the Unit Tests work with the NHibernate DAO classes, in a nearly transparent manner. This SessionManager.cs was adapted from a blog post by Petter Wiggle. The reference post titled ‘NHibernate Session handling in ASP.NET – the easy way’ is one of the examples of how not to implement SessionPerRequest as it uses the Global.asax file for initialization, rather than correctly using an IHttpModule. Now for the code (split into 3 section to ensure that it will print correctly):
The SessionManager gets its configuration data from the Unit Test project if "UnitTest" is in the application directory name, otherwise it performs a normal configuration and uses the web.config for the Web Application. It is that easy.
The map file is one method to notify NHibernate of the class to table mapping. Other methods are ConfORM or FluentNHibernate, but the map file was the first mechanism. Remember to set the Build Action for your map files to Embedded Resource so that they are included in the assembly file to be read by the SessionManager in the initialization process.
Here you can see the table diagram for the Person table in the SQL Server database.
The class diagram for the Person class shows how the map file uses both the table and the class definition to make NHibernate able to persist an instance of the Person class. Also note that the Person Class inherits from the Entity class.
I have borrowed the Entity class from the implementation of Jason Dentler, described earlier. This Entity class is slightly different from a number of Id providers used by NHibernate persistence classes in that it makes the setter for the Id property ‘protected’, rather than ‘public’. This means that the application code is not able to directly set the Id of a class instance, but that it can only be set by the DAO implementation. As a result the application is forced to use Data Transfer Objects (dto) to communicate from the UI to the persistence classes.
The PersonDto class diagram is shown below. The PersonID property maps to the Person.Id property of the persistence class, with all other properties lining up as expected.
The next 3 code snippets show how a dto is used to move data from a persistence class to a dto and then use that dto to populate a DataGrid. The function Get_PersonData fills a persistence class from the database using the ICriteria based GetByCriteria query and then uses a LINQ to Object function to fill the dto. Then the dto is passed to the DataGrid and then it is data bound in the method Fill_gvPerson.
The method _view_OnSaveEditPerson demonstrates the necessary steps to get data out of a dto and then to persist the user inputs. First it checks the value of txtPersonIdValue to determine if the data is from an instance that exists in the persistence layer, or is it a new instance – indicated by an empty value. Next the persistence class Person instance is fill using a GetByID function from the DAO implementation and then the data from the form fields is copy to the Person instance. Finally the Person instance is now saved.
While the sample solution is useful, it is definitely not enterprise ready. The main problem with this solution is that the Web Application has a knowledge of the persistence layer. The next step is to factor these calls to the BusinessServices project. Doing that will reduce the interdependencies and will increase the overall testability of the full application, as it is almost impossible to properly unit test code in the Web Application itself. Additionally further decoupling can be achieved by ensuring that all calls to the persistence layer are done through the DataServices layer.