[pMixins]

A lightweight open source Mixin and AOP framework for C#


Inheritance is often useful, but more often overused.

Bernie Sumption animator.js

Motivating [pMixins]

In the middle of 2012 I was working for a consulting company that focused on asp.net web applications. Almost of all our applications had to read and write data to a database for one reason or another and none of the applications did so in a consistent manner.

So when I had some down time I started working on creating a reusable data tier infrastructure that would standardize how our applications talked to a database. I have always liked the repository pattern so I went about implementing a class hierarchy to support it.

The Repository Base Class
After some initial trial and error I came up with a generic base repository class similar to this:

public abstract class BaseRepository<T> where T : IEntity
{
   protected abstract string ConnectionString {
      get;
   }
   protected void ExecuteQuery(Action<SqlConnection> query)
   {
      //Do Transaction Support / Error Handling / Logging
      using(var conn = new SqlConnection(ConnectionString)) {
         conn.Open();
         query(conn);
         conn.Close();
      }
   }
   //CRUD Methods:
   public abstract T GetByID(int id);
   public abstract IEnumerable<T> GetAll(int id);
   public abstract void Add(T Entity);
   public abstract void Update(T Entity);
   public abstract void Delete(T Entity);
}

I was initially quite satisfied with this. I had a single base class that defined my CRUD operations. All of these methods would go through the ExecuteQuery method which could add Transactions, Logging, Error Handling, etc. so I could get this standard. And I could easily create an overload, SqlStoredProcedureBaseRepository that would handle the basics for using Sql Stored Procedures. So to consume the repository, all you had to do was specify the name of the Stored Procedure for each method and the appropriate mapping functions:

public abstract class SqlStoredProcedureBaseRepository<T> : BaseRepository<T> where T : IEntity
{
   protected abstract string GetByIDStoredProcedureName {
      get;
   }
   protected abstract T MapDataReaderToEntity(SqlDataReader reader);
   protected abstract string AddStoredProcedureName {
      get;
   }
   protected abstract IEnumerable<SqlParameter> MapEntityToSqlParameters(T entity);
   public override T GetByID(int id)
   {
      var entity = default(T);
      ExecuteQuery(conn =>  {
         using(var cmd = conn.CreateCommand()) {
            cmd.CommandText = GetByIDStoredProcedureName;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("Id", id));
            entity = MapDataReaderToEntity(cmd.ExecuteReader());
         }
      });
      return entity;
   }
   public override void Add(T Entity)
   {
      ExecuteQuery(conn =>  {
         using(var cmd = conn.CreateCommand()) {
            cmd.CommandText = AddStoredProcedureName;
            cmd.CommandType = CommandType.StoredProcedure;
            foreach(var p in MapEntityToSqlParameters(Entity))
               cmd.Parameters.Add(p);
            cmd.ExecuteNonQuery();
         }
      });
   }
   //Other CRUD methods omitted for brevity
}

The Problem
I set about updating one of our existing projects to use the new BaseRepository. I immediately ran into a problem: business logic. I found an Entity, in this case it was a Twitter post, that could be Created, Read, and Deleted but never Updated. My initial reaction was to split up BaseRepository so the Update method would go into a new class: BaseRepositoryWithUpdate.

This worked for the Twitter use case, but as I continued I encountered more and more permutations of Entities that would only support subsets of CRUD. Create, Read, and Update, but not Delete. Create, Read but not Update or Delete. Read, Update and Delete, but not Create. There was no way to logically split up BaseRepository without ending up with something nasty like:

public class CreateReadButNotUpdateOrDelete : BaseRepository<ExampleEntity>
{
    public override void Update(ExampleEntity Entity)
    {
        throw new NotImplementedException("Don't Ever Call This Method!!");
    }
    public override void Delete(ExampleEntity Entity)
    {
        throw new NotImplementedException("Don't Ever Call This Method!!");
    }
}

This introduced a terrible code smell. Now anyone who wanted to use the CreateReadButNotUpdateOrDelete Repository had to know to never call the Update or Delete method. And if they did, their code would compile just fine but would throw a run time exception.

The Quest
I started searching for a better solution. I experimented with extension methods and marker interfaces, but this solution had testability limitations. I brushed up on object composition but found it to be too verbose and full of boilerplate code to be practical. I was introduced to Aspect Oriented Programming and tried Post Sharp, but found this the wrong tool for the job. I learned off mixins and found the re-mix project, but the syntax was too unwieldy.

I took what I had found and went to Stack Overflow: C# Object Composition - Removing Boilerplate Code . I received some interesting feedback but the big take away was lots of people had this problem, and no one had a proper solution for it.

The Solution
Shortly after posting the Stack Overflow question, I decided to try and create my own mixin project, which would greatly simplify using object composition and mitigate the need to use implementation inheritacne for code re-use.

In June 2013 I released my first proto-type, Intent Compositor. Intent Compositor met the initial criteria and certainly taught me a great deal. But it was more rigid and artificially limited than I liked, so in August 2013 I started work on [pMixins].

And now after two years of development, solving the Repository problem with [pMixins] can be seen in the Repository Recipe!