Posts Tagged NHibernate

How-To: Using the N* Stack, part 2

Last Saturday, I posted the first part in a series about building an ASP.NET MVC application from the ground up using NHibernate and Ninject. It dealt with setting up the structure of your solution and referencing some 3rd party assemblies.

In part 2, we’re going to set up the persistence object model. The persistence object model is a set of objects that we use to persist (save) data to the database.

Warning: This is a sample application. There are widely varying opinions on the correct structure for these types of applications. As with most advanced subjects in the ALT.NET space, Ayende has some great information on the difference between a persistence object model and a domain model. For the purposes of this series, they’re the same thing.

First, we build the structure of our persistence model as plain old CLR objects (POCO). I like to do this in the Visual Studio class designer. It helps keep me focused on the high-level entities and relationships instead of wandering off to do detailed implementation code.

Here’s the model we’ll start with:

image

Let’s look at the relationships between courses and sections. We have a one to many relationship from a Course to it’s Sections represented by an ICollection(Of Section) property in Course. We also have a many-to-one relationship from each section back to it’s Course represented by the Course property on Section.

Public Class Course

    Public Property Sections() As ICollection(Of Section)
        Get

        End Get
        Set(ByVal value As ICollection(Of Section))

        End Set
    End Property

End Class

Public Class Section

    Public Property Course() As Course
        Get

        End Get
        Set(ByVal value As Course)

        End Set
    End Property

    'Other properties here...

End Class
public class Course
{

    public ICollection<Section> Sections {
        get { }

        set { }

    }

}

public class Section
{

    public Course Course {
        get { }

        set { }

    }

    //Other properties here...

}

Now that we have all of that built, there’s a couple of small requirements to use these classes with NHibernate.

  1. All properties and methods must be overridable. That’s virtual for your C# folks.
  2. Unless you’re using a dependency injection bytecode provider, you need a parameter-less constructor. If you don’t know what a bytecode provider is, don’t worry about it. We’ll get in to it later on in the series. If you don’t have any constructors, you’re fine. There’s an implied parameterless constructor. As soon as you add a constructor with parameters, you’ll need to create one without parameters, just for NHibernate.
  3. You need some sort of identity property for your database primary key. This can be inherited from a base class, which is exactly what we’re going to do. Edit: Not true. Thanks for the correction Ayende!
  4. In the case of readonly properties, you have some options. You can tell NHibernate your naming convention for backing fields. I don’t like this. I prefer to make my properties read/write and make the setter protected. If you’re new to NHibernate, you’ve probably never seen this before.
    Public Class Course
        Inherits Entity
    
        Private m_Sections As ICollection(Of Section) = New HashSet(Of Section)
    
        Public Overridable Property Sections() As ICollection(Of Section)
            Get
                Return m_Sections
            End Get
            Protected Set(ByVal value As ICollection(Of Section))
                m_Sections = value
            End Set
        End Property
    
    End Class
    public class Course : Entity
    {
    
        private ICollection<Section> m_Sections = new HashSet<Section>();
    
        public virtual ICollection<Section> Sections {
            get { return m_Sections; }
            protected set { m_Sections = value; }
        }
    
    }

    This is how I set up all of my collection properties. You can manipulate the contents of the collection, but you can’t replace it with another instance without inheriting this class and overriding the property. If you were to make this property readonly, you’d have to configure NHibernate to write to m_Sections using reflection. It’s sort of a pain, and completely unnecessary. This is easier and accomplishes the same end result.

    Also, notice that we’re inheriting from a class called Entity. More on that later.

Let’s talk about the database for a minute. Each of these entity classes will eventually become a database table. What will you use for your primary keys? Fabio Maulo has a great post on the different NHibernate primary key generators. He also has this post about why identity columns probably are not the best choice.

So what’s a good choice? Well, that’s a matter of opinion. Thanks to NHibernate, I don’t go spelunking through the database much anymore, so I like guids. You really can use what you like, or rather, what your DBA likes.

Now, where are you going to put these primary keys in your objects? In my opinion, this is really a persistence detail – meaning your objects shouldn’t really be dealing with it. That’s why we’re going to keep it hidden away in the base class. Remember, we’re inheriting from Entity.

Public MustInherit Class Entity

    Private m_ID As Guid

    Public Overridable Property ID() As Guid
        Get
            Return m_ID
        End Get
        Protected Set(ByVal value As Guid)
            m_ID = value
        End Set
    End Property

End Class
public abstract class Entity
{

    private Guid m_ID;

    public virtual Guid ID {
        get { return m_ID; }
        protected set { m_ID = value; }
    }

}

That’s it for today’s post. In part 3, we’ll configure NHibernate and set up our database. For homework, we’re going to flesh out the other properties in our persistence model. Check out the source code in Visual Basic.NET or C#.

Tags: , , ,

How-To: Using the N* stack, part 1

This is the first post in a series where I show you step-by-step how to get your first ASP.NET MVC website up off the ground. By the end of this series, we’ll have a working web application for registering community college students. More importantly, you’ll have a template you can easily follow for your own projects.

In this first post, I’ll show you how to set up your visual studio solution.

In this series, we’ll use these tools:

  • ASP.NET MVC is a free, fully Microsoft-supported product that, unlike ASP.NET WebForms, gives you complete control over your application. You can use the Web Platform Installer or download the MSI installer package directly.
  • MVCContrib – This is the contrib project for ASP.NET MVC. It adds additional functionality to and makes ASP.NET MVC easier to use.
  • jQuery – This is an open-source javascript library that does just about everything, and supports every major modern browser out there. Yes, you hate javascript. You’re going to love jQuery. I promise. This is included in the ASP.NET MVC download.
  • NHibernate 2,1 is a well-known, mature, open source object relational mapper (ORM). It helps you get on with writing you application, instead of spending days, weeks, or even months writing a data access layer.
  • Fluent NHibernate – This is a library for configuring NHibernate using an english-like syntax. It saves you from hacking through dozens of XML configuration files. Scroll to the bottom of the downloads page and get the latest compiled binaries.
  • Ninject is my personal favorite dependency injection (DI) / inversion of control (IoC) framework. It allows you to automatically wire up services to your objects. If you’ve never done DI or IoC before, you’re going to have a great “ah-ha!” moment. We’ll be using version 1.

You will also need:

  • .NET Framework 3.5 SP1
  • Visual Studio 2008 SP1. The Web Dev Express version may also work. I haven’t tried it.
  • The latest version of NUnit
  • Any major database supported by NHibenate. This can range from Oracle to SQL Server to MySQL to SQLite. I’ll be using SQL server in my examples, but if you have a favorite, you can easily use that instead.

I also suggest you get some kind of source control. You’ll want to play around and experiment as we go along.

OK. You’ve downloaded all of that? Good. Let’s talk terminology for a minute.

  • MVC stands for Model-View-Controller. This separation of responsibilities allows you greater flexibility to adapt and change your application.
  • Model – This term refers to all of your entities – your business objects. In terms of a billing application, this would be your invoices, invoice items, customers, products, etc. – all of the “real-world things” your application represents.
  • View – Each view presents a specific business object in a specific way. For example, you may have a view for editing customer data and another for displaying an invoice. You can also think of views as the pages that make up your application.
  • Controller – Controllers are the glue that bind a view to a specific entity in your model. They are also responsible for all of the flow of your application from page to page.
  • Inversion of Control (IoC) is the concept that your objects do not explicitly create the services that they need. Instead, they get them from some container of services. Hence, the inversion. Your classes don’t specify a specific implementation of the service, only the type of service they need – an interface. This loose coupling allows you to easily swap out implementations of those services without having to touch every class that uses them. I’ve seen two major flavors of IoC: Service Locator and Dependency Injection.
  • A Service Locator is a central container where you specify which implementations of each service your application will use. Your objects request service implementations from the service locator. A service locator is typically a singleton, which is why I don’t like it.
  • Dependency Injection (DI) is a method of wiring your objects to the services they depend on as the object is built. These services are typically passed in as parameters on the object’s constructor. The object itself is built by the DI framework, in this case, Ninject. The process of building dependencies can be many layers deep. The Ninject Dojo has a great tutorial on dependency injection. If you’re new to IoC, it’s a great place to start learning. Once you have the “ah ha!” moment, the migraine will stop and you’ll never look at code the same again. I promise.

Setting up the solution

Disclaimer: This is how I have learned to set up my projects. I’m sure others have differing opinions. I’d love to hear them. I don’t claim to be an expert, just a curious professional looking to improve.

Setting up the project is fairly straight-forward. We’ll do almost everything through Visual Studio. Just follow these steps.

  1. Create the solution and web project

    In Visual Studio, start a new ASP.NET MVC Web Application. This template is added to Visual Studio when you install ASP.NET MVC. I’ll be calling my solution NStackExample.
    image

    There’s a few things to note here. First, we’re creating a solution directory. Second, notice how we’ve appended .Web to the name of our web project, but not the solution.

    This web project will contain all of the views. Despite the implied direction from Microsoft through the ASP.NET MVC template, it won’t contain the model or the controllers.

  2. Create a library directory

    Inside your solution directory, create a directory for all 3rd party libraries used in your project. I call mine Solution Items. The name you give it isn’t as important as the fact that you have one. So, in the example shown above, I would create the directory C:\Users\Jason\Documents\Visual Studio 2008\Projects\NStackExample\Solution items. Copy these 15 assemblies to the library directory:

    • From MVCContrib:
      • MVCContrib.dll
      • Microsoft.Web.Mvc.dll
      • System.Web.Abstractions.dll
      • System.Web.Mvc.dll
      • System.Web.Routing.dll
    • From NHibernate:
      • Antlr3.Runtime.dll
      • Iesi.Collections.dll
      • log4net.dll
      • NHibernate.dll
      • Castle.Core.dll
      • Castle.DynamicProxy2.dll
      • NHibernate.Bytecode.Castle.dll
    • FluentNHibernate.dll from Fluent NHibernate
    • From Ninject:
      • Ninject.Core.Dll
      • Ninject.Framework.Mvc.Dll
  3. Create the core project

    This is your main project. It will contain your model, as well as interfaces for any services and strategies your application will use. It will not contain the implementation of any of those services. Those go in separate, easily replaceable assemblies.

    Add a new “Class Library” project to your solution. We’ll call this project NStackExample.Core.

    Now, right click on the project and select properties, then click on the Application tab on the side. In the root namespace field, remove .Core.

    image
    We’re doing this so our entities will be named NStackExample.Entity1, NStackExample.Entity2, etc. but the assembly will be NStackExample.Core.dll, which better describes it’s purpose.

  4. Create the controller project

    Next, create another project specifically for the controllers of your MVC project. We’re going to call it NStackExample.Controllers. Yes, the Microsoft ASP.NET MVC project template already has a folder for them. We’re not going to use that folder because I think they should be better separated from the content of your website.

  5. Clean up your projects

    Delete all of these:

    • The Class.vb or Class.cs files in the Core and Controllers projects.
    • In the NStackExample.Web project, delete:
      • The Controllers folder and all of it’s contents.
      • The Models folder
      • The Microsoft AJAX script libraries in the Scripts folder
      • The Home and Account folders inside the Views folder
      • The LogOnUserControl in the Views folder

    image

  6. Set up your references

    This is pretty straight forward.

    1. First, in your web project, remove the references to System.Web.Abstractions, System.Web.Mvc, and System.Web.Routing.
    2. Next, in your web project, from the library directory we created in step 2, add references to these 10 assemblies:
      • log4net.dll
      • Microsoft.Web.Mvc.dll
      • MvcContrib.dll
      • NHibernat.Bytecode.Castle.dll
      • NHibernate.dll
      • Ninject.Core.dll
      • Ninject.Framework.Mvc.dll
      • System.Web.Abstractions.dll
      • System.Web.Mvc.dll
      • System.Web.Routing.dll
    3. In the web project, add references to the controllers project and the core project.
    4. In the controllers project, add references to these 3 assemblies:
      • log4net.dll
      • MvcContrib.dll
      • System.Web.Mvc.dll
    5. In the controllers project, add a reference to the core project.

Did you notice how we didn’t add any references in our core project? That’s intentional. When a project needs to reference your model or service interfaces, you don’t want to have required dependencies on other libraries and frameworks.

That’s it. Your solution is set up and you’re ready to start coding. In the next post, we’ll start building the model, configure NHibernate, and set up the database.

Jason

- Blogged-out for the night

Tags: , , , , ,

Hibernating Ninjas and Entity Ninjection AddIn

injectionAs I posted before, NHibernate 2.1 allows you to inject dependencies in to your entities through the constructor. The idea is that when NHibernate rehydrates your object graph, it uses your favorite IoC container to inject whatever strategies and services your entities may require.

The Unofficial AddIns for NHibernate project has implementations of NHibernate’s IBytecodeProvider interface to do Entity DI with Castle and Spring. Using these as a template, I’ve written an add-in for Entity DI using Ninject v2.

The code for this add-in basically falls in to two categories:

  1. Make NHibernate stop whining about parameters on the constructors.
  2. Creating instances of entities as they are being rehydrated from the database.

Constructor Parameters – Oh, the humanity!

We all know NHibernate makes a big freakin’ deal out of certain things – virtual / overridable methods and properties, and parameterless constructors. When you do constructor DI, the constructor will have parameters. It’s a fact.  Yes, you can inject your dependencies through properties, but don’t do it. You’ll spend months chasing NullReferenceExceptions.

So, how do we stop NHibernate from puking on entities that don’t have a parameterless constructor? Simple – We override the methods that do those checks. Thanks to some serious refactoring in NHibernate 2.1, it’s all in two places.

  1. DynProxyTypeValidator’s CheckHasVisibleDefaultConstructor method
  2. ReflectionOptimizer’s ThrowExceptionForNoDefaultCtor method

So, we sub-class those objects and override those methods to do nothing. There’s some other minor plumbing. Check out ProxyFactoryFactory in the attached source.

What’s this BytecodeProvider thing anyway?

From Fabio Maulo’s blog:

The BytecodeProvider has two responsibility: provide the ProxyFactoryFactory and provide the ReflectionOptimizer.

That’s exactly what we’re doing.

Besides providing our new ProxyTypeValidator, the ProxyFactoryFactory also returns an implementation of IProxyFactory. Since Ninject doesn’t do proxies, we have to wire in a proxy generator. Well, what’s a DI framework good for, if not to wire in services. IProxyFactory is fetched from the kernel. This means you can use Ninject for DI and still have your choice of proxy factories: Castle, Spring, or Linfu, so far.

The reflection optimizer is responsible for creating instances of our entities as they’re being rehydrated from the database. This is where we get in to the second part of code.

Let’s make some entities

Because Ninject has automatic self-binding baked in, this part is also insanely easy. Here’s the ReflectionOptimizer function where all of the magic happens:

        public override object CreateInstance()
        {
                return kernel.Get(mappedType);
        }

That’s it. Yes. Really. It’s that easy.

Well, not quite that easy. This changes the requirements for your entites in one very subtle and non-obvious way. In previous versions, and by default in this version, NHibernate always uses the parameterless constructor.

When using the NinjectBytecodeProvider, unless you decorate your entities with the Inject attribute, the constructor with the most parameters will be used. Remember – Unless you explicitly tell it otherwise, Ninject will choose the most complicated constructor it can find, even if it can’t resolve all of the dependencies.

Great! What now?

I’ve submited this code to the uNHAddIns project and posted about it in the Ninject group. Until it’s posted there, you can download it here.

That’s all the time we have today. Tune in to my next post, where I’ll show you how to build your own ASP.NET MVC project, and use this bytecode provider.

Jason
- Ninjecting entities since 2009

Tags: , , , ,