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

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

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

Custom AuthorizationHandler for SignalR Hubs

How to implement IAuthorizationRequirement for SignalR in Asp.Net Core v5.0 Been battling this for a couple of days, and eventually ended up raising an issue on Asp.Net Core gitHub  to find the answer. Wanting to do some custom authorization on a SignalR Hub when the client makes a connection (Hub is created) and when an endpoint (Hub method) is called:  I was assuming I could use the same Policy for both class & method attributes, but it ain't so - not because you can't, because you need the signatures to be different. Method implementation has a resource type of HubInnovationContext: I assumed class implementation would have a resource type of HubConnectionContext - client connects etc... This isn't the case, it's infact of type DefaultHttpContext . For me I don't even need that, it can be removed completely  from the inheritence signature and override implementation. Only other thing to note, and this could be a biggy, is the ordering of the statements in th