Using Database Repository Pattern with ActiveRecord with ActiveRecordMediator

This is a Re-Post from my older blog at geekswithblogs.

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<T>. 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<T> : IRepository<T> where T :class 
    {
        protected ActiveRecordMediator<T> mediator;

        public virtual void Save(T item)
        {
            ActiveRecordMediator<T>.Save(item);
            
        }
        public virtual T FindById(object id)
        {
            return ActiveRecordMediator<T>.FindByPrimaryKey(id);
        }
        public virtual T FindOne(params ICriterion[] criteria)
        {
            return ActiveRecordMediator<T>.FindOne(criteria);
        }
       public virtual T[] FindAll()
        {
            return ActiveRecordMediator<T>.FindAll();
        }

        public virtual int Count()
        {
            return ActiveRecordMediator<T>.Count();
        }
       
    }
}

Related Articles:

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

This entry was posted in ActiveRecord, Repository Pattern. Bookmark the permalink. Follow any comments here with the RSS feed for this post.