Using Database Repository Pattern with ActiveRecord with ActiveRecordMediator

Castle’s ActiveRecord frame work is an easy way to get introduced to NHibernate if you’re not familiar with setting up and using NHibernate (which I’m not).  However many people are not fond of the ActiveRecord pattern.  It can be a leaky abstraction, putting persistence related functions on your domain model is not a very clean separation of concerns for many people.  I tend to agree with this.  It really does depend on the complexity of your application.

When learning about AR I read a lot of blog entries or the documentation, people elude to how you can use AR API in a repository fashion, but I could find very few examples of how to uses.

It turns out there is an innocuous object within the API call ActiveRecordMediator.  This little guy has all of the persitance related methods you normally call directly on your ActiveRecord object.  With this object you can use a Repository style DAL.  Here is my simple BaseRepository that I inherit from to take advantage of ActiveRecordMediator.  You can extend this further of course, but it’s all I need at the moment.

public class BaseRepository : IRepository where T :class

    {

        protected ActiveRecordMediator mediator;

        public virtual void Save(T item)

        {

            ActiveRecordMediator.Save(item);

        }

        public virtual T FindById(object id)

        {

            return ActiveRecordMediator.FindByPrimaryKey(id);

        }

        public virtual T FindOne(params ICriterion[] criteria)

        {

            return ActiveRecordMediator.FindOne(criteria);

        }

        public virtual T[] FindAll()

        {

            return ActiveRecordMediator.FindAll();

        }

        public virtual int Count()

        {

            return ActiveRecordMediator.Count();

        }

    }

This article is part of the GWB Archives. Original Author: John Teague

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.