Skip to main content

Repository pattern - my preferred implementation...

Okay it's nothing new and not even original but I wouldn't to get down my currently preferred implementation of the repository pattern. I suppose this was prompted by a blog by Jimmy Bogard and Oren's statement a couple of months ago the repository pattern may be near then end of it's life.

I still think in the .Net world they have great relevance as most .Net devs can't organise code for toffee and when you try and introduce layering into an application the use of an explicit repository layer is the first layer they seem to understand.

So here is my current repository flavour - strawberry with a twist of lemon...


 public sealed class Repository<T1, T2> : IRepository<T1, T2> where T1 : IEntity<T2>
{
private readonly ISession _session;
private readonly string _traceType;

public Repository(IProvideSessions sessionFactory)
{
_traceType = string.Format("Repository<{0}, {1}>: ", typeof(T1).Name, typeof(T2).Name);
_session = sessionFactory.GetSession();
}

public T1 Get(T2 id)
{
Trace.WriteLine(string.Format("{0} Get - '{1}'.", _traceType, id));
return _session.Get<T1>(id);
}

public void Save(T1 instance)
{
Trace.WriteLine(string.Format("{0} Save - '{1}'.", _traceType, instance.Id));
_session.Save(instance);
}

public void Delete(T1 instance)
{
Trace.WriteLine(string.Format("{0} Delete - '{1}'.", _traceType, instance.Id));
_session.Delete(instance);
}

public T1 FindOne(IFindable findable)
{
Trace.WriteLine(string.Format("{0} FindOne, - '{1}'.", _traceType, findable.GetType().Name));
var criteria = findable.BuildCriteria();
return criteria.UniqueResult<T1>();
}

public IList<T1> FindAll(IFindable findable)
{
Trace.WriteLine(string.Format("{0} FindAll, - '{1}'.", _traceType, findable.GetType().Name));
var criteria = findable.BuildCriteria();
return criteria.List<T1>();
}
}

One of the first things to notice is the use of two generic types T1 & T2 - I'm not great at naming generic parameters so they never got better names. Hopefully it's obvious but T1 is the domain entity and T2 represents the 'Id' column for the entity (All DDD entities have Id's).

The other important feature is the 'FindOne' & 'FindAll' methods they take an implementation of the interface IFindable which performs the magic. Now this is where the generic repository starts to have a 'leaky abstraction' and this happens to be exposing nHibernate's ICriteria interface vai the IFindable interface. The implementation of the IFindable is responible for the creation of the NH criteria and returns this when requested, this is then executed by the repository and volia the results are returned.

So my current repository pattern is designed to be used with NH, but if a client dictates I can't use NH then I will modify the IFindable interface accordingly or I will terminate the contract depending on how I'm feeling :)

 public interface IFindable    {        ICriteria BuildCriteria();    }


An example of this could the a Findable class that returns an NH criteria that will return bank customers with a balance greater than million - Millionaires!



public sealed class FindValuedCustomers : IFindable
{
private readonly ISession _session;

public FindValuedCustomers(IProvideSessions sessionFactory)
{
_session = sessionFactory.GetSession();
}

public ICriteria BuildCriteria()
{
return _session.CreateCriteria(typeof(Account)).Add(Property.ForName("CurrentBalance").Gt(1000000));
}
}


Now I can see how Oren goes from this to the idea of just using NH Session anywhere in the code you previously used a Repository but I do think there is still some requirement to provide a layer & abstraction for testing purposes.

One other thing to note, I do believe the Repository pattern has valid uses outside of DDD, as Eric has stated most of the common patterns in DDD existed before the book.



Awkward Coder

Comments

Popular posts from this blog

WPF tips & tricks: Dispatcher thread performance

Not blogged for an age, and I received an email last week which provoked me back to life. It was a job spec for a WPF contract where they want help sorting out the performance of their app especially around grids and tabular data. I thought I'd shared some tips & tricks I've picked up along the way, these aren't probably going to solve any issues you might be having directly, but they might point you in the right direction when trying to find and resolve performance issues with a WPF app. First off, performance is something you shouldn't try and improve without evidence, and this means having evidence proving you've improved the performance - before & after metrics for example. Without this you're basically pissing into the wind, which can be fun from a developer point of view but bad for a project :) So, what do I mean by ' Dispatcher thread performance '? The 'dispatcher thread' or the 'UI thread' is probably the most

Showing a message box from a ViewModel in MVVM

I was doing a code review with a client last week for a WPF app using MVVM and they asked ' How can I show a message from the ViewModel? '. What follows is how I would (and have) solved the problem in the past. When I hear the words ' show a message... ' I instantly think you mean show a transient modal message box that requires the user input before continuing ' with something else ' - once the user has interacted with the message box it will disappear. The following solution only applies to this scenario. The first solution is the easiest but is very wrong from a separation perspective. It violates the ideas behind the Model-View-Controller pattern because it places View concerns inside the ViewModel - the ViewModel now knows about the type of the View and specifically it knows how to show a message box window: The second approach addresses this concern by introducing the idea of messaging\events between the ViewModel and the View. In the example below

Implementing a busy indicator using a visual overlay in MVVM

This is a technique we use at work to lock the UI whilst some long running process is happening - preventing the user clicking on stuff whilst it's retrieving or rendering data. Now we could have done this by launching a child dialog window but that feels rather out of date and clumsy, we wanted a more modern pattern similar to the way <div> overlays are done on the web. Imagine we have the following simple WPF app and when 'Click' is pressed a busy waiting overlay is shown for the duration entered into the text box. What I'm interested in here is not the actual UI element of the busy indicator but how I go about getting this to show & hide from when using MVVM. The actual UI elements are the standard Busy Indicator coming from the WPF Toolkit : The XAML behind this window is very simple, the important part is the ViewHost. As you can see the ViewHost uses a ContentPresenter element which is bound to the view model, IMainViewModel, it contains 3 child v