Spring.NET- Dapper micro ORM support

Here is code which shows how to extend Spring.NET’s AdoTemplate to enable Dapper micro ORM support. It is based on code & configuration presented in THIS post.

public delegate T DataContextDelegate<T>(DataContext command);
public delegate T IDbConnectionDelegate<T>(IDbConnection connection, IDbTransaction transaction);

public class ExtendedAdoTemplate : AdoTemplate
{
    public virtual T Execute<T>(IDbConnectionDelegate<T> del)
    {
        ConnectionTxPair connTxPair = ConnectionUtils.GetConnectionTxPair(DbProvider);

        return del(connTxPair.Connection, connTxPair.Transaction);
    }

    public virtual T Execute<T>(DataContextDelegate<T> del)
    {
        ConnectionTxPair connTxPair = ConnectionUtils.GetConnectionTxPair(DbProvider);

        using (var context = new DataContext(connTxPair.Connection))
        {
            context.Transaction = connTxPair.Transaction as DbTransaction;

            return del(context);
        }
    }
}

Usage example (imaginary reporting service):

[Transaction(IsolationLevel.ReadUncommitted, ReadOnly = true)]
public void RunReport(ReportInput input, Stream outputStream)
{
    var reportData = LinqAdoTemplate.Execute(delegate(IDbConnection conn, IDbTransaction tran)
    {
        var multi = conn.QueryMultiple("GetReport", param: input, transaction: tran, commandType: CommandType.StoredProcedure);

        var reportData1 = multi.Read<ProjectData1Row>()
            .ToList();
        var reportData2 = multi.Read<ProjectData2Row>()
            .ToList();
        var reportData3 = multi.Read<ProjectData3Row>()
            .ToList();

        return new
        {
            ProjectsInfo = reportData1,
            ProjectsMoreInfo = reportData2,
            ProjectsEvenMoreInfo = reportData3
        };
    });

    GeneratePDF(
        reportData.ProjectsInfo,
        reportData.ProjectsMoreInfo,
        reportData.ProjectsEvenMoreInfo,
        outputStream);
}

Leave a comment