Using the container scoping capablity of Autofac makes NHibernate session management a breeze. Obviously this only handles the most basic session-per-request scenario but we know that can cover a large percentage of most peoples requirements anyway. I am sure other containers could get to this functionality as well, but I was blown away by how easy it was aith Autofac. Below is my session management configuration:
builder.Register<NHibernateInstance>().SingletonScoped();
builder.Register(c => c.Resolve<NHibernateInstance>().CreateSession()).As<ISession>().ContainerScoped();
builder.RegisterGeneric(typeof (Repository<>)).As(typeof (IRepository<>)).ContainerScoped();
So the key points are:
- Plug in the Autofac HttpHandler for ASP.Net integration by following the instructions here
- Have a singleton instance of the NHibernate session factory (housed in my NHibernateInstance class)
- Have a method on that singleton registered instance that returns an ISession (CreateSession in my example)
- Configure a container scoped instance of the NHibernate ISession, thus ensuring that the created instance will not cross request boundaries
- Have the container dynamically inject the ISession into your IRepository implementation
For more information on container scoping in Autofac for ASP.Net web applications check out the Autofac wiki article.
In the previous to parts to this series (here and here) I showed the basic infrastructure framework for using Linq-based specifications with a flexible repository interface. In this article I dig deeper into the Expression based find functionality and it's implementation.
The Goal
Specification based query support on the repository is a great feature for encapsulation of any query logic. My major problem with this approach was the creation of trivial specifications on a per-domain-object basis. This would litter the code with specifications that had very little functionality contained within them. Generally this is not a bad thing but, in this instance, for the sake of maintainabilty and simplicity I wanted a to be able to perform ad-hoc queries.
The solution was to make my repository able to accept queries like :
var repository = new Repository<Person>(session);
var people = repository
.FindAll(p => p.Name == "steve");
The AdHoc specification
Since I have already made the decision that my MatchingCriteria are of type Expression, the AdHoc specification is trivial - but very cool. The implementation looks like :
public class AdHoc<T> : Specification<T> where T : IEntity
{
private readonly Expression<Func<T, bool>> expression;
public AdHoc(Expression<Func<T, bool>> expression)
{
this.expression = expression;
}
public override Expression<Func<T, bool>> MatchingCriteria
{
get { return expression; }
}
}
Simplifying the repository using the AdHoc specification
By utilising this simple but powerful specification class we can simplify the api to our IRepository. We are now able to add a FindOne and FindAll overload that accept Linq based queries in an AdHoc fashion. The implementation is as simple as :
public IQueryable<T> FindAll(Expression<Func<T, bool>> expression)
{
return FindAll(new AdHoc<T>(expression));
}
This functionality is able to be consumed in the following fashion (satisfying our goal for this task) :
var people = repository.FindAll(p => p.Name == "steve");
Conclusion
In combination with the flexibility built into the IRepository interface we now have a basis for a data access layer with maximum flexibility. Sql queries are created at execution time to reflect the criteria that we have applied through domain specifications - be they concrete or ad-hoc.
In Part 1 of this series I expressed my goal of a powerful Linq implementation for the specifications within my domain. In this part of the series I go into further detail and show I have implemented my repositories to support the pattern.
The IRepository definition
In the code below I have restricted my IRepository to be read-only for the purposes of the exercise. Obviously in reality there would be more functionality defined on this interface.
The use of the specification as a parameter to the Find methods is obvious. The use of an Expression is not so obvious at this stage and I will elaborate on this functionality later in the series.
public interface IRepository<T> where T : IEntity
{
T FindOne(Guid id);
T FindOne(Expression<Func<T, bool>> expression);
T FindOne(Specification<T> specification);
IQueryable<T> FindAll();
IQueryable<T> FindAll(Expression<Func<T, bool>> expression);
IQueryable<T> FindAll(Specification<T> specification);
}
The Repository
Implementing the repository means tying oneself to a particular Linq provider. In my case I chose Linq to NHibernate but switching it out for another implementation should be trivial.
See in the repository implementation that work is able to be integrated with the specifications by calling either SatisfyElementFrom (FindOne) of SatisfyElementsFrom (FindAll) and providing a candidate parameter provided by the Linq provider - in this case Linq to NHibernate provides a Queryable list proxy when we specify session.Linq().
public class Repository<T> : IRepository<T> where T : IEntity
{
private readonly ISession session;
public Repository(ISession session)
{
this.session = session;
}
public T FindOne(Guid id)
{
return session.Get<T>(id);
}
public T FindOne(Expression<Func<T, bool>> expression)
{
return FindOne(new AdHoc<T>(expression));
}
public T FindOne(Specification<T> specification)
{
return specification.SatisfyingElementFrom(session.Linq<T>());
}
public IQueryable<T> FindAll()
{
return (from t in session.Linq<T>() select t);
}
public IQueryable<T> FindAll(Expression<Func<T, bool>> expression)
{
return FindAll(new AdHoc<T>(expression));
}
public IQueryable<T> FindAll(Specification<T> specification)
{
return specification.SatisfyingElementsFrom(session.Linq<T>());
}
}
Conclusion
In this article I have shown an implementation of my repository facilitated by the use of Linq to NHibernate. The most striking part is the simplicity of the code. We have nicely seperated out our query concerns and the repository provides us with flexibility and also efficiency thanks to the power of Linq.
Disclaimer : I am unsure if what I am about to show here is a bridge too far in terms of bastardising the specification pattern ... it very well may be the case. However, Linq has provided a new paradigm that needs to be embraced, and sometimes that requires the tweaking of existing pratices and patterns.
Background Info
For some background on this article I recommend reading the following primers. I would never have to got to where I did without them. Please check out:
Implementing the Specification Pattern via Linq
[http://ubik.com.au/article/named/implementing_the_specification_pattern_with_linq]
Linq, the Specification Pattern and Encapsulation
[http://www.iridescence.no/post/Linq-the-Specification-Pattern-and-Encapsulation.aspx]
Implementing ORM-independent Linq queries
[http://rabdullin.com/implementing-orm-independent-linq-queries/]
The Goal
I wanted a flexible way to leverage the deferred execution power of Linq in my application. The logical place for this to occur was deep in the data access layer at the repository level. Also, as always, I wanted the ability to encapsulate my query logic into specifications and this became the real integration challenge with linq.
Specifications are easy to apply to existing in-memory collections - they fit that paradigm well. But at the lower level I knew linq could provide more power than what was previously possible with the traditional specification pattern. I wanted a way to leverage the deffered execution of Linq to drive my specifications for querying.
The Specification Class
My specification class is not dependent on any particular Linq to SQL provider. I chose to use Linq to NHibernate but that was a personal choice. I am quite sure that a switch to Linq-To-SQL would result in no modifications to any existing specifications. This provider agnostic specification implementation is a nice example of what a common language paradigm like Linq can provide.
Notice that the base abstract specification class handles all of the matching work for the specification. Any inheriting specification simply needs to specify their relevant MatchingCriteria. The SatisfyingElementFrom method (singular) simply enforces that a single result is returned. The bulk of the work is done in SatisfyingElementsFrom, which actually applies the criteria. Note that it is critical that the Matching criteria is of type Expression. This ensures we have access to the expression parsing power of Linq. Simply using a Func or a Predicate will break this implementation.
public abstract class Specification<T> where T : IEntity
{
public abstract Expression<Func<T, bool>> MatchingCriteria { get; }
public T SatisfyingElementFrom(IQueryable<T> candidates)
{
return SatisfyingElementsFrom(candidates).Single();
}
public IQueryable<T> SatisfyingElementsFrom(IQueryable<T> candidates)
{
return candidates.Where(MatchingCriteria).AsQueryable();
}
}
A simple specification
Below is the code for a simple specification implementation. Notice how it has no responsibility apart from specifying the criteria that it represents.
public class PersonById : Specification<Person>
{
private readonly Guid id;
public PersonById(Guid id)
{
this.id = id;
}
public override Expression<Func<Person, bool>> MatchingCriteria
{
get { return p => p.Id == id; }
}
}
Conclusion
So far I have demonstrated how to implement specification classes that have the potential to harness the power of Linq. Please follow the other parts of the series to see further implementation details - specifically the repository.
Whilst there is still ongoing debate about the merit of using regions, I have to admit that I have no strong leaning towards any side of the argument. However, I do need the ability to hide and show all of the regions in a class quickly and easily.
A trick that I first picked up when using VS2003 still works for me today and can quickly push you towards indifference in the debate as well.
This article written by Roland Weigelt (in 2003!) lists the code for some macros that can be simply assigned to a keyboard shortcut to help manage any regions you come across. Because, regardless of your stance on the issue, you will always come across regions somewhere.
Below I have assembled a short guide to installing and using the macros -
1. Copy all of the macro source code from the original article but only the module code itself (i.e ignoring the import statements and module declaration - these are added by VS automatically when you create a new module). The code below has been stolen from the original article and reproduced here for convenience.
' Toggles the current region surrounding the cursor
Sub ToggleParentRegion()
Dim objSelection As TextSelection
objSelection = DTE.ActiveDocument.Selection
Dim objPosition As EnvDTE.TextPoint
objPosition = objSelection.AnchorPoint
objSelection.SelectLine()
If (InStr(objSelection.Text.ToLower(), "#region") <> 0) Then ' Updated 14.08.2003
objSelection.MoveToPoint(objPosition)
DTE.ExecuteCommand("Edit.ToggleOutliningExpansion")
DTE.ActiveDocument.Selection.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn)
ElseIf (objSelection.FindText("#region", vsFindOptions.vsFindOptionsBackwards)) Then
DTE.ActiveDocument.Selection.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn)
DTE.ExecuteCommand("Edit.ToggleOutliningExpansion")
DTE.ActiveDocument.Selection.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn)
Else
objSelection.MoveToPoint(objPosition)
End If
End Sub
' Expands all regions in the current document
Sub ExpandAllRegions()
DTE.ExecuteCommand("Edit.StopOutlining")
DTE.ExecuteCommand("Edit.StartAutomaticOutlining")
End Sub
' Collapses all regions in the current document
Sub CollapseAllRegions()
ExpandAllRegions()
Dim objSelection As TextSelection
objSelection = DTE.ActiveDocument.Selection
objSelection.StartOfDocument()
While (objSelection.FindText("#region"))
objSelection.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn)
DTE.ExecuteCommand("Edit.ToggleOutliningExpansion")
objSelection.StartOfDocument()
End While
DTE.ActiveDocument.Selection.StartOfDocument()
End Sub
2. In Visual Studio (VS2008 in this example) open the Macros IDE (Alt-F11 or under Tools -> Macros)
3. In the Macros IDE, add a new macros module called RegionTools by right-clicking on MyMacros and select Add -> Add Module
4. Paste the code copied from above inside the module definition
5. Save and the close the Macros IDE
6. Now assign your keyboard shortcuts. Open the Options menu by opening Tools -> Options in Visual Studio
7. Under Environment in the tree menu (left hand side of the Options dialog), select Keyboard
8. Filter all of the available commands by typing RegionTools in the filter box

9. You should now see the 3 new macros that you added to the Macros IDE. And now you can assign them keyboard shortcuts at your whim. Personally I only use CollapseAllRegions (mapped to Ctrl+Shift+Num -) and ExpandAllRegions (mapped to Ctrl+Shift+Num +). But they are both of enormous benefit.
Now all that is left is for someone to tell me this has been built in to VS2008!
So after a lenghty layoff and many broken promises I am back into the blogging fold with a brand new screencast. I have been keen to demo Camtasia for a while and am pretty happy with the results. And it should make for a better end user experience because I am not a very good writer!
The video shows off some of the tricks, tools and techniques for TDD in .Net. It was cool to play with Gallio for the first time and I am loving its integration with Resharper. Very nice.
For best result watch the video in its original size (the quality if you do that is surprisingly good). To access the original size -
- Click the full screen button in the top right corner.
- Click the menu button in the bottom left corner.
- Then in the menu along the top of the screen click 'Original size'.
Alternatively, if you prefer to watch the video offline you can download from Viddler by clicking
here.