In my previous post about the Specification pattern I showed how the pattern works and how to implement it. I’ve also uploaded a sample project on Specification to GitHub. But my implementation suffers from a serious fallback: you cannot generate database queries using it, instead you have to pull everything into memory and iterate over that. Luckily you haven’t have to write and parse your own expression trees (although it could be a nice experience). There’s a nice library on CodePlex called LinqSpecs which does just that. Disclaimer: I have nothing to do with LinqSpecs and didn’t take part of its development. I just found it extremely useful so I thought I’d share it in my blog.
The LinqSpecs implementation is a little bit different than what I wrote. First it uses an abstract base class instead of an interface. Then it doesn’t use methods to concatenate the various specifications, instead it relies on overloading the logical operators. But the most important thing is that it doesn’t return a simple Boolean value whether or not your candidate satisfies the specification. It returns an expression instead. The method looks like as follows:
For me it was a bit unclear how to work with this, but here’s a concrete implementation:
And here’s how to use it in an arbitrary repository:
Since the specification returns an expression you don’t have to provide one in the Where extension method on the datacontext, so the syntax feels more right. One issue arises with unit testing, since testing the previous version was much more intuitive. I wouldn’t like to copy a discussion here, instead here’s a link from the project page on unit testing specifications.