Label your services!

Here’s a code snippet showing a little habit of mine — something I do to all my domain and application services:

public interface IPortfolioRepository : IDomainService
{
    ...
}

public interface IPortfolioAdministrationService : IApplicationService
{
    ...
}

What’s in these base interfaces? Nothing. They are just labels, used to help make make object roles explicit:

public interface IApplicationService {}
public interface IDomainService {}

Why is this a good idea?

  1. It helps makes implicit concepts — e.g. this is a domain service — explicit.
  2. It grants you freedom with your class names, without having to suffix everything with Service or Event.
  3. It lets you do cool stuff like write integration tests to check all your application services are registered correctly.

They’re not only limited to services, by the way. Use them for aggregate roots, entities, value types, and other types of objects:

public interface IPortfolio : IAggregateRoot
{
    ...
}

public interface IPortfolio : IEntity
{
    ...
}

public class Money : IValueType
{
    ...
}

public class BookAddedToPortfolio : IDomainEvent
{
    ...
}

Udi Dahan’s Making Roles Explicit is a must-see presentation on this subject, if you haven’t already seen it. In fact, this example is only a small subset of what you can do with this technique.

March 31, 2010

2 Comments

Matt on April 1, 2010 at 6:36 am.

Another neat trick here is to use this to do auto-registration of components in your IoC container – “for these assemblies, register all types that implement these interfaces” – some containers support this natively – Autofac (v2.x) and StructureMap, and I’m sure there’s others – convention over configuration…

Richard on April 1, 2010 at 10:21 am.

Matt : that’s right! Also I just remembered Ayende’s automatic NHibernate aggregate root locking uses this approach too.

Leave Your Comment

Your email will not be published or shared. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>