NHibernate is very flexible

…but it does impose limitations on your domain model.

Most of these limitations, however, like the need for public/ internal/ protected members to be virtual, and the requirement for a default constructor to exist with at least protected accessibility, are not that hard to adhere to and usually don’t interfere with what you would do if there were no rules at all.

One of the limitations, however, can be pretty significant – Ayende describes the problem here, using the term “ghost objects”.

But, as I am about to show, this significance only arises if you follow a certain style of coding, which you should usually avoid!

Short explanation of the problem

When NHibernate lazy-loads an entity from the db (i.e. when you call session.Load<TEntity>(id) or when an entity in your session references something through a lazy-loaded association), it does so by providing an instance of a runtime-generated type, which acts as a proxy.

The first time you access something on the proxy, it gets “hydrated”, which is just a fancy way of saying that the data will be loaded from the database.

This would be fine and dandy, if it weren’t for the fact that the proxy is a runtime-generated subclass of your entity, which – in cases where inheritance is involved – will be a sibling to the other derived classes. Consider the simple inheritance hierarchy on the sketch to the right which in code could be something like so:

– and then NHibernate will generate something along the lines of this (fake :)) class signature:

See the problem? Here’s the problem:

This means that this kind of runtime type checking will fail in those circumstances where the entity is a lazy-loaded reference of the supertype, and the following will FAIL:

One possible solution

The other day, Ayende blogged about a recent addition to NHibernate, namely lazy-loaded properties. This allows an entity to be partially hydrated, intercepting calls to certain properties to lazy-load the relevant fields on demand.

This feature is great when storing LOBs alongside the other fields on an entity, but it also laid the ground for his most recent addition, which is the ability to lazy-load an association by setting lazy="no-proxy" on it.

This way, NHibernate will not build a proxy, but instead it will intercept the property getter and load the entity at that point in time, thus being able to return the exact (sub)type of the loaded entity.

Now this seems to solve our problems, but let’s zoom out a bit … why did we have a problem in the first place? Our problem was actually that we failed to write object-oriented code, but instead we wrote a brittle piece of code that would fail at runtime whenever someone added a new subtype, thus violating the Liskov substitution principle. Moreover it just feels wrong to implement business logic that reflects on types!

What to do then?

Well, how about making your code polymorphic? The logic above could be easily rewritten as:

– which moves the logic of yielding name as a oneliner into the class hierarchy, allowing us to always get a name from a LegalEntity.

What if I really really need a concrete instance?

Then you should use the nifty visitor pattern to extract what you need. In the example above, I would need to add the following additions:

This way, we’re taking advantage of the fact that each subclass knows its own concrete instance, thus allowing it to pass itself to the visitor we passed in.

This is the preferred solution when the logic you’re writing doesn’t belong inside the actual entitiy class, like e.g. when you want to convert the entity to an editable view object, because this will make your code break at compile time if someone adds a new specialization, thus requiring each piece of logic to handle that specialization as well.

Oh, and if you’re a Java guy, you might be missing the ability to create an inline anonymous visitor within the scope of the current method, but that can be easily emulated by a generic visitor, like so:

– which would allow you to write inline typesafe code like this:

Only thing missing now is the ability to return a value in one line depending on the subclass. Well, the generic visitor can be used for that as well by adding the following:

– allowing you to write code like this:

– and still have the benefit of compile-time safety that all specializations have been handled.

When to reflect on types?

IMO you should only reflect on types in business logic when it’s a shortcut that doesn’t break the semantics of your code. What do I mean by that? Well, e.g. the implementation of the extension method System.Linq.Enumerable.Count<T>() looks something like this:

This way, providing the number of items is accelerated for certain implementations of IEnumerable&lt;T&gt; because the information is already there, and for other types there’s no way to avoid manually counting.

Conclusion

I don’t think I will be using the new lazy="no-proxy" feature, because if I need it, I think it is a sign that my design has a bad smell to it, and I should either go for polymorphism or using a visitor.

C# vs. Clojure vs. Ruby & Scala

Short preface: at a job interview, Zach Cox was told to aggregate words and word counts from a bunch of files into two files, sorted alphabetically and by word count respectively, which he did in Ruby and Scala. This led Lau Bjørn Jensen to do the same thing in Clojure, which apparantly sparked other people to do it in Java, Python etc.

Inspired by the afore mentioned problem, and an extended train ride home (thank you, Danish National Railways!!), I decided to see what a C# (v. 3) version could look like:

Weighing in at 36 lines and executing in 10.2 seconds (on my Intel Core 2 laptop with 4 GB RAM), I think this is a pretty clear and performant alternative to the other languages mentioned.

Simple and pragmatic event bus with Castle Windsor

Almost always, when writing even the simplest of systems, the need arises for some kind of event publishing/subscription mechanism. There are of course many ways to achieve this, but I have found that Castle Windsor can provide everything that I need to build a simple, yet incredibly powerful event bus.

Consider this example from the real world: mortgage deeds follow many paths through our mortgage deed administration system, and one of them is purchase for the administrator’s own portfolio. Upon recording the purchase, it is crucial that the debtors are enlisted in our subscription at the Central Office Of Civil Registration (CPR in Danish), allowing us to receive updates whenever people change names or move without telling us.

A naive implementation of the Record method on the Purchase could look like this:

– but this is ugly! Enlisting the debtors has no direct relation to the logic of how to record a purchase, and when this requirement came, this implementation caused numerous tests to break. You could of course argue that our tests should not rely on the record method, but that was however the case, and it was a real P.I.T.A. to implement this.

Moreover, this approach forces us to grab our service locator inside a domain entity, which is really bad for too many reasons to mention here.

What we SHOULD have done, and what I have been doing ever since, is to create a simple event bus that resolves handlers to messages through Windsor (actually directly through the kernel because it is automatically injected). This way, I could have implemented the record method like this:

– and then this method would never change again (at least not for the wrong reasons)…

Then I have my simple event bus mediator (just an ounce of indirection, allowing my entities to be unaware of the service locator):

– which, depending on the bool inside the static EventBusConfiguration class, will be either a fake bus that swallows all its messages, or the real deal:

This means that subscribing to a message is as simple as registering implementations of this:

in my Windsor Container, e.g. the handler that enlists people in our subscription at the Central Office Of Civil Registration:

This is really cool, because it allows one to build systems where logic is deliciously decoupled, and you can add stuff, and then some more stuff, and the new stuff will not break the old stuff, because it doesn’t interfere with it.

Moreover, if you feel like extending it a little bit, it shouldn’t take that much of an effort to publish the events into a message queue for other systems to handle. If, for example, it took a while to process something, then I would definitely benefit from letting another process take care of that while my web request continues. Or if I wanted to update my data warehouse, I would build an aggregator in another process that did batch updates of the warehouse.

Oh, and this is one of the reasons that I would not hesitate to choose Castle Windsor if I were allowed to bring only one thing to a deserted island… you can build almost anything with a cool IoC container.

Getting started with Fluent NHibernate

Why

I have loved NHibernate right from when I first learned how to use it, and I have loved NHibernate beneath Castle ActiveRecord since I found out that ActiveRecord could reduce the pain I felt because of NHibernate’s .hbm.xmhell.

However, using Castle ActiveRecord requires you to “pollute” your otherwise beautiful and pure domain model with database mapping metadata in the form of .NET attributes. If you are a PI kind of kind, this might be too much to ask. But if you (like me) are willing to relax your ideals a bit to gain the extra productivity, you might be happy to do so – even though it hurts your feelings a little bit every time you have to punch in that [Property(Access == PropertyAccess.FieldCamelCase)]-attribute for the 100th time…

But there is another option: Fluent NHibernate – an option that embraces the philosophy of “convention over configuration”, which seems to be getting a lot of attention these days in the .NET world.

EDIT: Oh yeah, and now it’s here.

How

If you know NHibernate, you know that you use it like this:

  1. Create a Configuration.
  2. Use the configuration to build an ISessionFactory which you store somewhere.
  3. And then use that session factory repeatedly to open ISessions which in turn are used to do stuff with the DB.

So, what can Fluent NHibernate do for you? Well, FNH is actually pretty simple – it helps with the Configuration part of NHibernate. As soon as the Configuration is finished, Fluent NHibernate is out, and from then on it’s pure NHibernate again.

First, I will show a short example – and then I will explain how much is actually accomplished by issuing these ridiculously simple statements. Behold:

If you look at the statements above, I can tell you that it configures FNH to assume the following:

  • All of my entities can be found in the assembly containing Base inside any namespace containing the string “Entities”.
  • All of my entities derive from Base, which is just a very simple entity layer supertype containing nothing more than an Id property of type Guid.
  • Any conventions found in the same assembly as Base will be used by FNH to alter the mappings.

Is that it? Well almost… The code above will make FNH map everything as good as it can, but I still want to alter the mapping in certain places – and that is done through the conventions found in my entity asseembly. At the moment I have 2 conventions:

  1. CascadeAttributeConvention, which is an IHasManyConvention and an IReferenceConvention that looks over any one-to-many and many-to-one relations in my domain, setting cascade to all or all-delete-orphan if it finds a CascadeAttribute on the property.

    This allows me to do stuff like

    and expect the collection of band members to live and die and be updated with its aggregate, Band.

  2. PluralizeTableNamesConvention, which is an implementation of IClassConvention I use to pluralize table names. It contains code like this:

    where the Pluralize method does whichever magic is required to pluralize names from my domain (usually by appending an “s”: Band => Bands, BandMember => BandMembers etc.).

And that is it!

I expect a few more conventions to come along as development progresses – e.g. in other projects I have run into the need to be able to specify that one string should be nvarchar(255) and another string nvarchar(8192) in the DB, which I have solved with an IPropertyConvention that looks for the presence of a LengthAttribute containing the desired length.

And that is why I really like Fluent NHibernate – it allows me to leverage the most powerful ORM alive in the easiest possible way, making NHibernate feel lean and lightweight, encouraging me to follow conventions in my codebase. What’s not to like?

Book review: ASP.NET MVC 1.0 Quickly

This book is exactly what its title says: a quick introduction to ASP.NET MVC. A natural implication is that it cannot cover that much material, and it seems Maarten went for breadth instead of depth.

In my opinion, when a book chooses to be a “quick guide”, it should focus more on showing the preferred ways to do stuff. Instead, this book seems to have too much ViewData["stuff"] = fluff going on. Why bother wasting pages showing all the tedious, error-prone, hard-to-maintain ways to do stuff when there is so little space?

asp.net.mvc.quickly.quickly

If I were to author a book on ASP.NET MVC, I would focus on explaining ASP.NET MVC from the extensibility points and out. For example, System.Web.Mvc.Controller is just one way to implement the IController interface, and so on. I think that would provide a much more wholistic image of the framework, and the extensibility points is where ASP.NET MVC shines. I don’t think Maarten’s book really shows where the framework shines.

I enjoyed the chapter on using existing ASP.NET features though, and, not being an ASP.NET guy at all, I think I learned some stuff there.

My conclusion is that this book is absolutely for beginners, and that the code samples in the book should not be taken literally, because almost none of them are examples on what the community considers best practice.

Title: ASP.NET MVC 1.0 Quickly
Author: Maarten Balliauw
ISBN 10/13: 184719754X / 978-1847197542
Publisher: Packt Publishing

My favorite ASP.NET MVC hooks #2: Action filter attributes

Another simple place to hook your stuff in to the framework is action filters. An action filter is an attribute that derives from ActionFilterAttribute which is a convenience class containing the following methods for you to override:

A lot of the examples around the internet show how to use action filters to restrict access to controller actions or how to apply caching. I won’t do that here, because those concerns are boring. No, we care about how to make life easy for ourselves and how to write testable, non-breakable, maintenance-and-wrist-friendly code. That is, we reserve the right to be lazy.

A fine example on how to be lazy is by letting action filters fetch data for you to avoid repetitive repository gymnastics in every controller action – and I am actually going to be very lazy right now, because I wrote two posts on this topic earlier:

  1. How to avoid duplicate data fecthing with ASP.NET MVC
  2. Another way to avoid duplicate data fetching with ASP.NET MVC

My favorite ASP.NET MVC hooks #1: Controller factory

My favorite hook in the ASP.NET MVC framework is the controller factory. I like it so much because it serves as a very simple entry point to the application, thus providing the perfect place to insert an IoC container. My container of choice is Castle Windsor – not because I have tried any other container – I really can’t say that I have – but because I just happened to be introduced by a colleague to Windsor, and I have yet to experience anything it can’t do for me!

An ASP.NET MVC controller factory is an implementation of the IControllerFactory interface – a simple interface with two methods: one that provides an IController given a string and some more stuff, and one that allows the controller to clean up any resources it might have allocated. The interface looks like this:

As you can see, it provides a means to return a controller, given all sorts of information about the current request and what could be resolved as the controllerName from the request URL.

ASP.NET MVC accesses the controller factory via the ControllerBuilder class – so if we want to provide our own controller factory, we must install the factory before any requests get served. An obvious place to do this, is the Application_Start method inside the global.asax.cs file. This way our controller factory will be installed every time the web application starts up.

The controller factory can be set in two ways: 1) By providing the type of the factory, and 2) By providing an instance of the factory. Then it’s up to you if you want to let ASP. NET MVC instantiate the factory. I usually do it like this:

– and let ASP.NET MVC instantiate and store a singleton instance of my factory.

My controller factory implementation looks like this:

Very simple. It takes the string, that was resolved as the controller name – e.g. “home”, “hOme”, “HOME” or whatever – and converts it to lower case, and then it uses that to look up a controller in my container. This means that all my controllers are registered in the container, and they will have all their dependencies automatically resolved when the container creates each instance.

A controller registration might look like this:

Simple – yet incredibly effective!

Creating a Windows service with Topshelf

Update: This post still gets a fair amount of traffic, so I’d like to direct your attention towards my newer post on TopShelf 2.0: On The Bus With MassTransit #1
Update: Please go to the updated guide to Topshelf, which covers how to get started with Topshelf 3

Just wanted to share my experiences regard ing the super cool mini framework, Topshelf – a bi-product from the development of MassTransit. When Dru and the other guys were working on MassTransit, they needed to create Windows services a lot, which led to the separation of the Windows service stuff from the other stuff – and now they call it Topshelf.

You use Topshelf by creating a console application. In the Main method, you create a configuration, which you hand over to Topshelf. Then, everything just works as expected.

Topshelf requires that you to use an IoC container hidden behind the common service locator interface, which is neat because then it’s up to you to decide which container to use. In this example, I am using Windsor.

Creating a service is as simple as this:

Everything in the snippet above works as expected. Note how I create my Windsor container and store it behind WindsorServiceLocator, which is my trivial implementation of the IServiceLocator interface. This way, Topshelf will pull the specified service type(s) ( SomeService in the sample) from the container, and call the specified methods to start/stop (and possibly pause/resume) the service.

Note also how I specify that my service has a dependency on message queueing – neat!

Running and debugging the service is as easy as executing the .exe.

Installing/uninstalling can be done with

Nifty!

Respect your test code #3: Make your tests orthogonal

When two things are orthogonal, it means that the angle between them is 90 degrees – at least in spaces with 3 dimensions or less. So when two vectors are orthogonal, they satisfy the property that there is no way to use the first one to express even the tiniest bit of what the other one expresses.

That is also how we should write our application code: methods and classes should be orthogonal to one another – i.e. no class should try to express what another class already expresses either in part or whole – therefore each class and each method should have only one responsibility, and thus one reason to change.

And test code is real code.

The corollary is that our tests should have only one single reponsibility as well.

That is why I hate tests that look like this:

Notice how this test is actually fairly decently structured – at least that’s what it initiallt looks like… but it actually tests a lot of things: it checks that the output of the DueTermsFinder is what it expects, testing the MortgageDeedRepository indirectly as well – and then it goes on to test the TermDebitRecorder … sigh!

If (when!) one of these classes changes at some point, because the requirements have changed or whatever, the test will break for no good reason. The test should break because you have introduced a bug, not because you made a change in some related functionality.

That is why I usually follow the pattern of AAA: Arrange, Act, Assert. Each test should be divided into discrete steps corresponding to 1) Arranging some data, 2) Triggering a computation or some state change, 3) Asserting that the outcome was what we expected. And if I am feeling idealistic that day, I also follow the principle of putting only one assertion at the end of each test.

I try to never do AAAAA (Arrance, Act, Assert, Act Assert) or AAAAAA, or AAAAAAA which is even worse.

Every test should have only one reason to break.

Respect your test code #2: Create base classes for your test fixtures

When writing code, I often end up introducing a layer supertype – i.e. a base class with functionality shared by all implementations in that particular layer in my application.

This also holds for my test code – and why shouldn’t it? Test code is as real as real code, so the same rules apply and it should benefit from the same pain killers as we implement in our application code.

For example when testing repositories and services that need to query the database, I can save myself a lot of writing by stuffing all the boring NHibernate push-ups in a DbTestFixture supertype – this includes building a configuration that connects to a test database, building a session factory, storing that session factory somewhere, re-creating the entire database schema in the test fixture setup, and running each test in a transaction that is automatically rolled back at the end of each test + a few convenience methods that allow me to flush the current session etc.

The DbTestFixture might look something like this (note that all my repositories take an instance of ISessionProvider in their ctor – that’s how they obtain the currently ongoing session, which is why I have a TestSessionProvider to inject into repositories under test):

Then a fictional repository test might look as simple as this:

Note how DbTestFixture flushes in all the right places so I don’t need to worry about that.

This test fixture supertype can be used for all my database access tests, as well as integration testing. But what about unit tests? I am using Rhino Mocks, so my unit test fixture base looks like this:

Real simple – it just stores my MockRepository and gives me a few shortcuts to the mocks I care for. Then I inherit this further to ease testing e.g. my ASP.NET MVC controllers like this:

As you can see, I make it a real “fixture” – the controllers I am about to test will fit into this fixture like a glove, and I will certainly never forget to instantiate my controller only once, because I start out by implemeting that part in the implementation of the CreateController method.

A controller test might look like this: