Handling Messages

To provide execution logic for messages define a class inheriting from IMessageHandler<T>. During the library initialization routine the assemblies in the current working directory are automatically scanned for classes implementing this interface. Once a message is put into the execution lib the appropriate message handlers are called.

Defining a Message Handler
A simple message handler may look like this.

public class CreateReportHandler : IMessageHandler<CreateReportMessage>
{
  public void Handle(CreateReportMessage message)
  {
    Console.WriteLine("Writing Report: {0}", message.Title);
  }
}

More than one handler may exist for the same message. In this case both handlers are executed, one after the other. If you want to ensure they are executed in a specific order use the FirstExecute<T>() method as described on the boostrapping page.

Message handlers do not have to be assigned to a concrete message type. It is perfectly well to write a message handler for a message base class or interface. To write a handler which is called for every kind of object added, define a message handler class using IMessageHandler<object>.

public class LogHandler : IMessageHandler<object>
{
  public void Handle(object message)
  {
    Console.WriteLine("Received message of type {0}", message.GetType().Name);
  }
}

Injecting External Dependencies
To interact with external dependencies it is recommended to make use of the dependency injection (DI) container. To do this, those dependencies have to be configured first within the container. After that they automatically become available in your handlers. Here is an example using the default StructureMap container.

// this method has be called before a message is put into the execution library.
public void RegisterDependencies()
{
  ObjectFactory.Container.Configure(x => x.For<IInvoicePrinter>().Singleton().Use<InvoicePrinter>());
}

// message handler capable of printing a specific invoice
public class PrintInvoiceHandler : IMessageHandler<PrintInvoice>
{
  private readonly IInvoicePrinter _printer;

  // handler constructor.
  public PrintInvoiceHandler(IInvoicePrinter printer)
  {
    // store injected instance for later use.
    _printer = printer;
  }

  public void Handle(PrintInvoice message)
  {
    // execute logic to print invoice.
    _printer.Print(message.InvoiceId);
  }
}

Last edited Jul 15, 2012 at 10:33 AM by domo42, version 5

Comments

No comments yet.