Yet another way to manage your NHibernate ISessionFactory

So here is my current UnitOfWork implementation.  This one makes use of the somewhat new current_session_context_class feature. I think this is quite simple compared to some of the others you will find.

public interface IUnitOfWork : IDisposable
    {
        IUnitOfWork Start();
        void BeginTransaction();
        void CommitTransaction();
        void RollbackTransaction();
    }
public class UnitOfWork : IUnitOfWork
    {
        #region Dependencies

        public ISessionFactory SessionFactory
        {
            get;
            set;
        }

        #endregion

        #region IUnitOfWork Members

        public virtual void BeginTransaction()
        {
            var session = SessionFactory.GetCurrentSession();
            if ( !session.Transaction.IsActive )
            {
                session.BeginTransaction();
            }
        }

        public virtual void CommitTransaction()
        {
            var session = SessionFactory.GetCurrentSession();
            if ( session.Transaction.IsActive )
            {
                session.Transaction.Commit();
            }
        }

        public void RollbackTransaction()
        {
            var session = SessionFactory.GetCurrentSession();
            if ( session.Transaction.IsActive )
            {
                session.Transaction.Rollback();
            }
        }

        public IUnitOfWork Start()
        {
            if ( !CurrentSessionContext.HasBind(SessionFactory) )
            {
                var session = SessionFactory.OpenSession();
                session.FlushMode = FlushMode.Commit;
                CurrentSessionContext.Bind(session);
            }
            return this;
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            var session = CurrentSessionContext.Unbind(SessionFactory);
            var transaction = session.Transaction;
            if ( transaction.IsActive )
            {
                transaction.Dispose();
            }
            session.Dispose();
        }

        #endregion
    }

All that’s required is this in the hibernate config section:

(for web apps):

<property name="current_session_context_class">web</property>

(for pretty much anything else): 

<property name="current_session_context_class">thread_static</property>

 

and just the barebones bootstrapping:

var sessionFactory = new Configuration().Configure().BuildSessionFactory();
            

Of course, to get this to work you need to register that sessionFactory instance into your IoC container, and register the UnitOfWork type with the container with a transient lifecycle.

 

From there you can either explicitly create and dispose IUnitOfWork instances for each operation, or set up a HttpModule to create one at the start of each request and dispose of it in the end_request event.

Current session context does not extend class CurrentSessionContext

If you’re trying to use NHibernate’s current_session_context_class configuration property, and you read somewhere that you can use “managed_web”, you might see the above HibernateException message.  Strangely, you can simply use “web”.

Session factory does not implement ISessionFactoryImplementor

If you see this error message while trying to check if your NHibernate ISessionFactory “HasBind” to the CurrentSessionContext, if probably means your ISessionFactory is null.   One of those mysterious error messages that leads you down the wrong track.

MushMud.com – High Level Architecture

(Note – this is part of a series on MushMud.com – an ASP.NET/MVC/DDD Example.  Be sure to read the introduction.)

From 1,000 feet the architecture looks like this:

High Level View of the MushMud Architecture

and the solution like this:

(Note the root namespace is “MusicCompany” – that was what I named it before MushMud came along.  Plus I don’t like the code-base so coupled to a specific domain name…)

Let’s start with Core.

The Core is what I like to think of as the heart of the application – where essential functionality if the system is implemented.    The Core is where the domain model lives.  The domain-model consists of the entities that represent the mental-model we have of our domain – things like Artists, Works, Licenses, Images and Audio Files.   In terms of code, the main job of an entity is to enforce the invariant rules of the domain.  The specifics of how the domain entity classes are designed and how they work together will be addressed later.  The domain entities are the most essential part of the system, and deserve a blog post to themselves.

In addition to the domain entities, we also need a couple of other types of classes to get the core work done:  Factories to help create new instances of entities, and Domain-Services to perform work involving multiple entities, factories and other external services.

A central part of this domain deals with audio files, formats, conversions and so forth.   Most of this functionality is available in external libraries and open source code which I access through the domain services.

Here’s a snapshot of  part of the Core project:

MushMud Core

Note that the Services are defined as interfaces.  For example the IMP3StreamService defines an interface for a service that performs data conversion between wave and mp3 encoded streams.

snapshot of IMP3StreamService interface

An actual implementation of this is in the MusicCompany.Core.Services.AudioConversion project, which utilizes a runtime-callable-wrapper of the LAME library (lame_enc.dll).  There are similar interfaces and implementations for FLAC, Ogg and WAVE formats.  I also use this same strategy for generating torrent files:

ITorrentFileService interface

… with an implementation based on the MonoTorrent library.   Here I pass in a CollectionWork (which is a domain entity) and get back a byte array representing the torrent definition which I can either write to disk or stream out.

Next I’ll address the Service Layer.

Not to be confused with Domain Services, the Service Layer is the surface area that is exposed to the user interface layers.  Basically the service layer exposes an API that my web layer uses to get data in and out.   This is a fundamental aspect to my overall architectural design: The core domain model is not used in the UI.  Instead, a service layer based on requests and responses is exposed to the clients. I don’t pass entities in and out of the service layer – it takes in commands and queries and returns responses and data-transfer objects (DTOs).   Getting to this point was a significant breakthrough in my architectural thinking, and is a concept that I think is being promoted by some really smart people.   By building my service layer this way, I get several huge advantages:

  1. I can use the command pattern for each API operation.   This promotes a testable design that follows the single-responsibility principle and promotes a beautiful level of intent and cohesion in the service layer classes.
  2. I don’t have to worry about data-binding issues in my entities.  When doing data binding you often need special constructs like parameterless constructors, getters and setters for every field,  property-changing notification, and hooks into UI-validation systems.  I don’t want any of that in my entities, and I’ll go into more detail why later.   Using a DTO or command object, I can easily databind to them because they are just simple data containers and by nature are essentially just get/set properties with a parameterlesss constructor.
  3. I don’t have to worry about the UI code calling methods on my entites – methods that perform domain logic that could potentially screw stuff up if used out of context.  (Anti-Corruption Layer)
  4. If I want to switch to a sliverlight or a smart-client front end I can easily do so.  (OK, maybe this is  a YAGNI)

To accomplish this, I use the Agatha Request/Response Service Layer created by Davy Brion.  Since this is a web app, I went with client-and-server-in-the-same-process configuration.

Here are the projects in the service layer:

Service Layer projects

The MusicCompany.Common project contiains classes that are references by both the consumer of the service layer (the UI) and the actual service layer processes (server components).   The NHib project is to support reading theViewModel (DTOs) from the database – I don’t map my entities to DTOs, in fact I have two models – one for queries and one for executing commands.  Or, as I sometimes think of it, a read model and a transactional model.   I’ll get more into this later, as well.

A typical command looks like this:

CreateArtist command class

Here we have the CreateArtistCommand, which inherits from CommandRequestBase, and CreateArtistCommandResponse, which inherits CommandResponseBase.  My commands are not one-way, fire-and-forget type commands – I almost always want a response so I know it executed correctly, and sometimes for some additional data from the result of the command.  This command has is constructed by the client when a user wants to create a new Artist entity.  The properties of the command (OwningPersonName, ArtistName, Bio) are the essential data needed by the domain layer to perform this action.  After the artist is created, the response sent back contains the Artist name – why?  because sometimes the domain layer will need to make some adjustments to the string that the user supplied and we want to indicate what the name was actually saved as.   Other uses of the response would be like “number of records affected”, etc.

The CommandRequestBase has the additional data that needs to be in all Commands – namely the context of command which lets us know who is issuing the command so that authentication and authorization can be done.  By default, the context is anonymous.

CommandRequestBase class

And now, without further ado, the handler:

CreateArtistCommandHandler class

Pretty simple, eh?  I love the one-method class.   One thing to note is that I’m using the NHibernate ISession directly here, rather than using a Repository interface.  This is something I contemplated quite a bit, and went back and forth on.  I think, at the time I was reading a lot of Ayende which influenced the decision.  If this were a larger, more “enterprisey” app I would probably go all out and use a repository for the sake of strict layering.

One great thing about Agatha, is that all I have to write are the command class, the command-response class and the command handler.  Agatha takes care of all the plumbing to wire this all together, so that my UI just needs to create the command and hand it over to a request dispatcher instance (the client DOES NOT ever reference the command handlers).

Now lets look at Queries.

Actually, first I want to show a snapshot of what the project actually looks like when you’re in there:

Command and Query classes in the project

Lots of files, huh?  The nice thing is, each is for one distinct operation.  I’d rather have this that a couple of classes with 20 or 30 methods each!

OK, a Query:

An example of a query object

Same pattern as the command.   A request and a response.  The Request (the actual query object constructed by the client) contains a single property, ArtistIdentifier.  This is the “parameter” for the query.   If I need to add another parameter to the criteria, I just need to add a new property to query object.  Compare that with a method on a repository or service that takes in x number of parameters…

The response to this query returns an IPagedList of TopLevelWorkSummaryView objects.  So what’s a TopLevelWorkSummaryView?  This is essentially a DTO that contains the data needed to display works in a list.  The “top level” refers to works that do not have a parent work, such as a Collection (aka “album”) or a Single (song released as a single).  Since all songs are Works, we don’t want to list songs that are part of a parent collection in this query, hence the TopLevel notion.

Now for the handler:

QueryHandler example class

I’m using NHibernate.Linq here to query the data store for TopLevelWorkSummaryView objects that have an ArtistIdentifier matching the value in the request.  TopLevelWorkSummaryView is a View in my database.   This is what led to the xxxView nomenclature for the DTO classes.  I realize this could be somewhat confusing compared to ViewModels in the MVC sense.  Maybe next time I would name these xxxDTO.  I also could actually persist these DTOs in a document database that I update with asynchronous events fired from the domain model, but I don’t need that degree of scalability yet.  But, the groundwork is there if I ever need it.

Now for the UI.

The UI is where I actually spent the most time in this app, after the domain modeling.  For one thing, I was learning ASP.NET MVC, which has a bit of learning curve.  And also, I was learning jQuery, which is awesome but takes a little getting used to coming from ASP.NET Ajax.  And I think that’s good – concentrate on the user experience and the presentation rather than worry about plumbing and infrastructure.

The Website project is laid out like a typical MVC project with controllers, views and viewmodels.   One interesting aspect is my ExtendedController, which is a base class for my controllers.   Here is a snippet:

Extended Controller snippet

The virtual ProcessRequest method is used by the concrete controllers to send all commands and queries to the service layer.  So, for example the Index method of the home controller is like this:
Index method

In this case my “model” is an IndexViewModel.  I went with the single view model per view pattern, so each view has it’s own view model with properties for all the data it needs.  The home page needs two lists of works – the new releases and the  most popular works, which are part of the ViewModel which the view can easily consume.

NEXT:  The Domain Model – Commands and Transactions

MushMud.com – Functional Overview

(Note – this is part of a series on MushMud.com – an ASP.NET/MVC/DDD Example.  Be sure to read the introduction.)

Without going into too much detail, I’ll describe the basic functionality of the website.

  1. List musical works with summary information and links to download, listen and get more information.  Here’s a screenshot of the list-view:
    example of list view
    I want the user to be able to listen to a song or an entire collection right on the list page, so that they can continue to read about the artist or browse other works while the audio is playing.    To keep the design fairly clean, I don’t list all the tracks in a collection by default – instead I provide a link to expand the track list :

    track list

  2. List both collection works (i.e “albums”) and single works (“singles”)
  3. Link to an artist-profile page for each artist
  4. Track the number of times each work is played and downloaded, and then rank the works in order of most plays/downloads.  This will allow me to display the stats in quick-summary form on lists, and also provide detailed stats for the user who manages the artist.  And of course a “Charts” page:
    Example of charts page
  5. Allow users to manage multiple artist profiles, and manage the works (upload songs, edit collections, etc) for each of their artists.   This deviates slightly from the typical user-account-per-profile pattern used by most sites.  I want a single user to be able to manage multiple artists, AND allow multiple users to have the ability to manage a single artist.  This will allow, for example, each band member to be logged in using their own personal account and build up the content  (works, images, bios, etc) for the artists they manage.   Perhaps the user who initially created the artist profile can determine the roles the other users will have.Once logged in, the user will start on their “Your Music” page.  (I decided to go with the “Your” idiom as opposed to the “My”, after reading the Yahoo design patterns stuff).  From here you can edit the profiles and manage the works of each of your artists, as well as view recent activity:YourMusic page example (the artist images here are the default image  - I know, pretty lame…)
  6. The user can add a new Collection:
    add collection example
    … and then add songs by uploading audio files.  The titles, tags, and other descriptors can then be edited, as well as the order of tracks.
  7. Allow users to select the type of license they want to use for each work.  The choices for now will be creative commons licenses.

So – pretty simple.  One interesting aspect is the notion of a work, which can be either a collection or a single.  This seems like a potentially effective use of inheritance.

NEXT:  High Level Architecture

MushMud.com – An ASP.NET/MVC/DDD example

I recently launched my pet project, MushMud.com.  It’s a music-sharing community featuring free and legal music downloads.  I know, it’s not the most original thing out there –  I’m mainly doing this for my own education and to allow me to demonstrate some architectural principles that I’ve been thinking about for a while.  Essentially the goals of the project are to:

  1. Try out ASP.NET MVC
  2. Attempt a true Domain Driven Design (DDD)
  3. Show how I might architect a real-world app
  4. Learn jQuery
  5. Try my hand at building a modern, “web 2.0″-ish UI
  6. Provide a real working website that hopefully some people might actually use and enjoy
  7. Provide a permanent digital home to some of my childhood home-recordings

The series:

Functional Overview

High level architecture

The Domain Model – Commands and Transactions(Coming Soon)

The Query Model – Optimized for Reads (Coming Soon)

The Service Layer (Coming Soon)

User Interface (Coming Soon)

Conculsion – The Good, Bad and Ugly (Coming Soon)

Getting WordPress working on IIS 7.0

So far I’m really liking WordPress. I’ve had to make a couple of tweaks, though, to get it working on my IIS 7.0 host.

1. In the index.php file. change
require('./wp-blog-header.php');
to
require('wp-blog-header.php');

Simple enough.

To get it working with LiveWriter, similar edits need to be made in xmlrpc.php:

include('wp-load.php');

Spring.NET based IContainer for Agatha

One of the nice things about the Agatha framework is the ability to use whichever Dependency Injection / IoC Container you want.  To do so, you just need to implement the Agatha.Common.InversionOfControl.IContainer interface with a class that uses your IoC container.   Out of the box you get IContainer implementations based on Castle Windsor, Unity, Structure Map and a couple of others.  However, if for some reason you’re using Spring.NET (well, I was …) you’ll need an IContainer that uses Spring.NET’s IApplicationContext.  Here’s what I came up with.

namespace Agatha.Spring
{
    /// <summary> 
    /// Spring.NET Implementation of Agatha.Common.InversionOfControl.IContainer. 
    /// When an Agatha Configuration initializes, it registers various objects here, 
    /// including all RequestHandlers it finds in the ServiceLayer assembly. 
    /// This implementation is desinged to be used in conjunction with traditional 
    /// XML based configuration of spring objects, so when asked to register an object 
    /// it checks to see if it already has it.  In this way we can configure certain 
    /// request handlers with interceptors as needed and still have Agatha wire up the rest. 
    /// </summary> 
    public class SpringContainer : IContainer
    { 

        private static readonly IDictionary<string, string> keyNameMap = new Dictionary<string, string>(); 

        private IConfigurableApplicationContext GetContext()
        {
            return (IConfigurableApplicationContext) ContextRegistry.GetContext();
        } 

        private string GetPreferredRegistrationKey(Type type)
        {
            return type.FullName;
        } 

        private string GetAlternateRegistrationKey(Type type)
        {
            return type.Name;
        } 

        private string GetResolutionKey(Type type)
        {
            string preferredKey = this.GetPreferredRegistrationKey(type);
            if ( this.GetContext().ContainsObject(preferredKey) )
            {
                return preferredKey;
            }
            else if ( keyNameMap.ContainsKey(preferredKey) )
            {
                return keyNameMap[preferredKey];
            }
            else
            {
                return GetAlternateRegistrationKey(type);
            }
        } 

        #region IContainer Members 

        public void Register<TComponent, TImplementation>(Lifestyle lifestyle)
        {
            Register(typeof(TComponent), typeof(TImplementation), lifestyle);
        } 

        public void Register(Type componentType, Type implementationType, Lifestyle lifeStyle)
        {
            string key = this.GetPreferredRegistrationKey(componentType);
            IConfigurableApplicationContext context = this.GetContext();
            if ( !context.ContainsObject(key) )
            {
                string existingName = context.GetObjectNamesForType(componentType).SingleOrDefault();
                if ( !string.IsNullOrEmpty(existingName) )
                {
                    keyNameMap.Add(key, existingName);
                }
                else
                {
                    IObjectDefinitionFactory objectDefinitionFactory = new DefaultObjectDefinitionFactory();
                    ObjectDefinitionBuilder builder = ObjectDefinitionBuilder.RootObjectDefinition(objectDefinitionFactory, implementationType);
                    builder.SetAutowireMode(AutoWiringMode.AutoDetect);
                    builder.SetDependencyCheck(DependencyCheckingMode.None);
                    builder.SetSingleton(lifeStyle == Lifestyle.Singleton);
                    context.ObjectFactory.RegisterObjectDefinition(key, builder.ObjectDefinition);
                }
            }
        } 

        public void RegisterInstance<TComponent>(TComponent instance)
        {
            RegisterInstance(typeof(TComponent), instance);
        } 

        public void RegisterInstance(Type componentType, object instance)
        {
            string key = this.GetPreferredRegistrationKey(componentType);
            if ( !this.GetContext().ContainsObject(key) )
            {
                this.GetContext().ObjectFactory.RegisterSingleton(key, instance);
            }
        } 

        public void Release(object component)
        {
            var disposable = component as IDisposable;
            if ( disposable != null )
            {
                disposable.Dispose();
            }
        } 

        public object Resolve(Type componentType)
        {
            IConfigurableApplicationContext context = this.GetContext();
            string key = this.GetResolutionKey(componentType);
            var component = context.GetObject(key);
            return component;
        } 

        public TComponent Resolve<TComponent>()
        {
            return (TComponent) Resolve(typeof(TComponent));
        } 

        #endregion
    }
}

I know it’s a bit odd, especially the whole GetResolutionKey deal.  Since I wanted this to work with my existing, XML based configuration, I needed to be able to handle objects registered with a couple of different keying strategies.  (This all stems from the annoying fact that Spring.NET uses strings as keys, and not actual Types like other containers let you.)

The only part that was at all tricky is the code in the Register method.  When using Spring.NET you almost never need to go through all this,  but use the XML configuration instead.

No Javascript in DotNetNuke?

I noticed a strange thing on my DNN site – the Login link didn’t work.  No error, nothing.  I was able to get logged in using the old /?ctl=login trick, and then noticed that lots of other things were broken.  I realized that none of the javascript was working.  This explains the login link, since it’s an ASP.NET LinkButton, which uses javascript to do the postback.   (why they used  a linkbutton and not a normal hyperlink is the subject of another post).

It was IIS 7.0 Integrated Pipeline mode.  I switched that off and went back to classic mode, and now it all works.

Strange….