Ryan LanciauxNew Media Mercenary

RhinoCommons, NHibernate and ASP.NET MVC Part 4 - The MVC Application

May 26, 2008 by ryan

Finally we're to the point where we can see all our hard work come together. We have most of the hard work done but we still have a lot of ground to cover. If you haven't been following along, please check out Setting Up The Assemblies, Configuring the Application and Developing the Model.

Unit of Work

In some of my initial tests with NHibernate and ASP.NET MVC Pattern I kept seeing the benefits of having a Unit of Work or Session Per Request (that is opening and closing the NHibernate session at the begining and end of the http request respectively). To Recap a little, I started to write my own Session Per Request, however, Chad Myers pointed me to the Rhino Commons project which already implemented this. I think it's worthwhile becuase I don't really like putting NHibernate session code in my controller plus as Martin Fowler writes

A Unit of Work keeps track of everything you do during a business transaction that can affect the database. When you're done, it figures out everything that needs to be done to alter the database as a result of your work.

Luckily, with RhinoCommons, it's pretty easy to implement this pattern (check out Ayende's post on this). In a standard web forms application, we would normally create a Global.aspx that inherits UnitOfWorkApplication. Since we're using ASP.NET MVC, however, we don't necessarily want to go that route. As Michael Hanney notes on his post on MVC and Castle we can have our Global.asax inherit from UnitOfWorkApplication.

 

    public class GlobalApplication : UnitOfWorkApplication

    {

 

        public override void Application_Start(object sender, EventArgs e

        { 

            base.Application_Start(sender, e); 

            RegisterRoutes(RouteTable.Routes); 

        }

...

     }

If you know of another way to do this, please be sure to let me know. Also, the routing still works as it normally would -- we're just running this code first to instantiate the UnitOfWork.

In our controllers we can call our reference our Hibernate repositories and classes without specifying an ISession.

        public ActionResult InsertProductGroup(string Title)

        {

            ProductGroup pg = new ProductGroup();

            pg.Title = Title;

            Repository<ProductGroup>.Save(pg);

            UnitOfWork.Current.Flush();

            return RenderView("AddProductGroup");

        }

Notice we're still flushing our data -- but it makes the controllers a LOT cleaner. Imagine if we had to instantiate and clean up our session in each controller.

One further thing, the UnitOfWorkApplication supports both short and long conversations. I'm not going to go too much into that but if your application requires keeping objects around for a couple HTTP Requests before saving to the database Long Conversation may be the way to go. See Ayende's Wiki for more on this

NHibernate Query Generator
In the first post of this series we looked at what it takes to setup NHibernate Query Generator (NHQG from here out). Now we get to use it to make some really nice looking code (in a later post, however, we'll be using LINQ to NHibernate). If we've set up the tool as mentioned in the first post (listed earlier), all we have to do is run the tool and make sure the generated code is added to the project.

NHQG lets us use a fluent interface to set filters on our Hibernate queries; this results in code that, in my opinion, is very easy to write and understand later on. If we wanted to Find one Product with a specific title, our code would look something like this:

        public ActionResult ViewProduct(string ID)

        {

            var p = Repository<Product>.FindOne(Where.Product.Title == ID);

            if (p != null)

            {

                return RenderView("DisplayProduct",

                                  p); 

            }

            return RenderView("DisplayProduct");

        }

The Where.Product.Title == ID is all from the NHQG autogenerated code. Now we actually have something to show for all our configuration and setup work. Soon, we're going to take a look at using LINQ to NHibernate instead of NHQG. In the meantime, I have checked all the code in to my svn at Assembla. My standard disclaimer on demo code applies here too :) This is just demo code for the sake of example. Some of it is far from ideal but great for learning.

Check out / update with SubVersion from the following location: http://svn2.assembla.com/svn/NHibernateTest


kick it on DotNetKicks.com



Related posts

Comments

May 27. 2008 11:49

Travis

I noticed you used Active Record, any reason why you chose that over Repository and Mapping Files method? Am I going to run into any snags going that route?

Travis

May 27. 2008 11:56

Ryan Lanciaux

@Travis I used ActiveRecord over mappings mainly for the sake of example but also because of the AR Repository. I don't know that you'll run into any snags but your domain will not be as pure due to the mapping attributes.

Ryan Lanciaux

May 28. 2008 02:57

pingback

Pingback from blog.cwa.me.uk

Reflective Perspective - Chris Alcock » The Morning Brew #102

blog.cwa.me.uk

May 29. 2008 09:30

Scott

Hey, thanks for doing this series. I think I'm going to have to learn something from you. Finally. Ha!

Scott

June 2. 2008 16:31

pingback

Pingback from code-inside.de

Wöchentliche Rundablage: ASP.NET MVC, .NET, ADO.NET Data Services, Silverlight, WPF… | Code-Inside Blog

code-inside.de

June 6. 2008 07:28

pingback

Pingback from allcoolblogs.com

RhinoCommons, NHibernate and ASP.NET MVC Part 5 - LINQ to NHibernate

allcoolblogs.com

July 29. 2008 18:18

Steve

The mapping files can be a real pain sometimes. Can you still use SchemaExport and SchemaUpdate with ActiveRecord? I'm thinking about trying it but I don't really want to couple the domain with the database implementation.

This project is worth keeping an eye on. You define your mappings in a seperate class using lambda's and the XML files get generated at run time.
http://code.google.com/p/fluent-nhibernate/
info: codebetter.com/.../...-errors-with-nhibernate.aspx

Steve

July 29. 2008 20:49

pingback

Pingback from hsidev.wordpress.com

To (ASP.NET)MVC or not to MVC (or, ASP.NET MVC Hyperlink Acupuncture) « HSI Developer Blog

hsidev.wordpress.com

July 31. 2008 18:26

pingback

Pingback from hsidev.wordpress.com

So you want to learn NHibernate? - Part 1 of 1, The Links « HSI Developer Blog

hsidev.wordpress.com

August 8. 2008 15:28

pingback

Pingback from thefreakparade.com

So you want to learn NHibernate? (or, NHibernate Hyperlink Acupuncture) | The Freak Parade

thefreakparade.com

November 22. 2008 05:02

water damage

Great post dear..
thanks for sharing.

water damage

November 22. 2008 08:47

shopping

you used Active Record, any reason why you chose that over Repository and Mapping Files method? Am I going to run into any snags going that route?
<a href="www.filter-outlet.com/">shopping</a>

shopping

November 22. 2008 09:30

Refrigerator Water Filters

i am getting error in this code sir
public class GlobalApplication : UnitOfWorkApplication
{

public override void Application_Start(object sender, EventArgs e)
{
base.Application_Start(sender, e);
RegisterRoutes(RouteTable.Routes);
}
...
}

Refrigerator Water Filters

November 22. 2008 15:26

US Personals

Thanks for sharing this, finally i could learn someting from you.
<a href="http://www.uspersonals.com/">US Personals</a>

US Personals

November 25. 2008 01:04

car hifi

Pingback from hsidev.wordpress.com

To (ASP.NET)MVC or not to MVC (or, ASP.NET MVC Hyperlink Acupuncture) « HSI Developer Blog

car hifi

June 16. 2009 22:30

pingback

Pingback from fixmycrediteasily.info

RhinoCommons NHibernate and ASP NET MVC Part 4 The MVC Application | fix my credit

fixmycrediteasily.info

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

July 3. 2009 20:23





© 2008 Ryan Lanciaux :: powered by BlogEngine.NET