Monthly Archives: October 2012

Extending MicroLite with custom Listeners

MicroLite provides a number of methods to allow custom code to be called during the internal pipeline, one of these is the IListener interface. The IListener interface is actually used by MicroLite to manage object identifiers (e.g. MsSql Identity).

The IListener interface defines a number of methods which you can implement:

  • void AfterInsert(object instance, object executeScalarResult);
  • void BeforeDelete(object instance);
  • void BeforeDelete(object instance, SqlQuery sqlQuery);
  • void BeforeInsert(object instance);
  • void BeforeInsert(object instance, SqlQuery sqlQuery);
  • void BeforeUpdate(object instance);
  • void BeforeUpdate(object instance, SqlQuery sqlQuery);

To save having empty method implementations in your class, you can inherit from the abstract Listener class which implements the IListener methods as virtual methods so you can just override the ones you need.

Lets say for example, that we have a requirement that some entities should have a created date and a created by property. In order to avoid having to set these properties throughout our application before we call ISession.Insert(), we can create a listener which MicroLite will invoke prior to inserting the record into the database.

Firstly, lets define an interface for our created date and created by:

public interface ICreated
    DateTime Created { get; set; }
    string CreatedBy { get; set; }

We can then create a Listener which can deal with this interface:

public class AuditCreatedListener : MicroLite.Listeners.Listener
    protected override BeforeInsert(object instance)
        // cast the instance safely in case not all entities implement ICreated.
        var created = instance as ICreated;

        if (created != null)
            created.Created = DateTime.Now;
            created.CreatedBy = Environment.UserName;

We can the register the listener, so in your application startup (where you call Configure):

using MicroLite.Listeners;


This will tell MicroLite to invoke your listener.

This article was written for version 2.0.0 of the MicroLite framework.