You are currently browsing the category archive for the 'Castle' category.

In our projects we’re using Castle’s Automatic Transaction Management facility (ATM). This facility allows to declaratively define transaction boundaries: by marking a method by a specific attribute the call to this method will be wrapped in a transaction, so that a transaction will be opened before calling the method and committed right after finishing method execution.

In code, it looks like this:

  1: [Transactional]
  2: public class Foo
  3: {
  4:     [Transaction]
  5:     public virtual void Bar()
  6:     {
  7:         // Do something in a transaction
  8:     }
  9: }
 10: 

Let’s suppose that later, we want to test this code. Say, we want to verify that code in Foo.Bar() method is executed in a transaction. Moreover, we want to assure that the marking attributes will not be deleted accidentally.

We can test that within two aspects. First – an integration test: a real application part will be spawned and a call will be performed. After, we should verify that changes was committed by transaction. It takes time to run such a test (integration test usually runs slower) and effort to write & verify such a test. Second way to test that – is to check presence or required attributes. This will be a fast unit test that will just check that attribute is still applied to a method.

Those methods complements each other. Ideally, it should be both written.

Let’s see how we can verify that attributes required by ATM are applied to required methods.

First, we’ve defined the API that we want to use to do our check:

  1: CustomAssertions.ShouldUseATM<Foo>(foo => foo.Bar());

Yes, you see it right, we want to make it type save, refactor-able and nice looking.

This helper class should verify next assumptions, all required by ATM:

  • Tested class should be marked with TransactionalAttribute;
  • Method should be marked by TransactionAttribute;
  • Method should be virtual.

Solution we came to this problem is the next class:

  1: public static partial class CustomAssertions
  2: {
  3:     public static void ShouldUseATM<T>(Expression<Action<T>> methodExpression) where T : class
  4:     {
  5:         ThrowIfTypeNotMarkedAsTransactional(typeof (T));
  6:
  7:         var methodInfo = ((MethodCallExpression) methodExpression.Body).Method;
  8:
  9:         ThrowIfMethodIsNotMarkedWithTransactionAttribute(methodInfo);
 10:         ThrowIfMethodMarkedWithTransactionAttributeIsVirtual(methodInfo);
 11:     }
 12:
 13:     private static void ThrowIfTypeNotMarkedAsTransactional(Type classType)
 14:     {
 15:         object[] foundAttributes = classType.GetCustomAttributes(typeof (TransactionalAttribute), false);
 16:         if (foundAttributes.Length == 0)
 17:             Assert.Fail("The type '{0}' is not marked with [Transactional] attribute", classType.Name);
 18:     }
 19:
 20:     private static void ThrowIfMethodIsNotMarkedWithTransactionAttribute(MethodInfo info)
 21:     {
 22:         var found = info.GetCustomAttributes(typeof (TransactionAttribute), false);
 23:         if (found.Length == 0)
 24:             Assert.Fail("Method '{0}' from '{1}' type is not marked with [Transaction] attribute",
 25:                         info.Name,
 26:                         info.DeclaringType.Name);
 27:     }
 28:
 29:     private static void ThrowIfMethodMarkedWithTransactionAttributeIsVirtual(MethodBase methodInfo)
 30:     {
 31:         if (methodInfo.IsVirtual && !methodInfo.IsFinal)
 32:             return;
 33:
 34:         Assert.Fail("Method '{0}' from '{1}' type is marked with [Transaction] attribute, but is not declared as virtual.",
 35:                     methodInfo.Name,
 36:                     methodInfo.DeclaringType.Name);
 37:     }
 38: }
 39: 

So far, we’re pleased with how it works for us.

I’m evaluating the NServiceBus communication framework for using it in some parts of application that we’re working on. I like the messaging infrastructure that it offers and how it all is implemented – behind a simple interface is hidden a modular, extensible, reliable and extremely powerful messaging engine. Sure, like any other framework, it has his own pitfalls and places that requires a special knowledge about how things works to use it efficiently.

One of those tricky places is his configuration system. To start use NServiceBus you have to do few steps to properly configure it. You have to use 2-3 “app.config” configuration sections with approximately 10-15 various parameters and few configuration classes provided by NServiceBus.

Another place that make me stuck is his integration with IoC (Inversion of Control) container. It has an abstraction over all container stuff, so you can pretty easily create an adapter to use it with container of your choice. I don’t like how this abstraction is used and implemented, a bit unnatural for my habits on how to put container to work.

Anyway, we have to deal with it, and use the NServiceBus with Castle Windsor container. As I said to do that you have to create an adapter for IBuilder interface. The NServiceBus Contrib project contains a patch that do this, but it is done in a completely wrong way – by mimicking the adapter for Spring framework. Bad, bad, bad…

So let’s take our big gun – Binsor from Rhino.Tools (I wrote about here) that should do all dirty work by configuring NServiceBus and integrating it in our existing Windsor container. The link to VS solution with all code shown here is provided at the end of the page.

Here we go – how to configure a subscriber for Pub/Sub interactions:

1. Binsor configuration (.boo file):

import System.Reflection
import NServiceBus
import NServiceBus.Unicast
import NServiceBus.Serialization
import NServiceBus.Serializers.Binary
import NServiceBus.Unicast.Transport
import NServiceBus.Unicast.Transport.Msmq
import NServiceBus.Unicast.Subscriptions
import NServiceBus.Unicast.Subscriptions.Msmq

import ObjectBuilder
import nServiceBus.CastleIntegration

component IBus, NServiceBus.Unicast.UnicastBus:
    MessageOwners = {"Messages":"messagebus"}
    MessageHandlerAssemblies = [Assembly.Load("Subscriber1")]

component ITransport, MsmqTransport:
    InputQueue = "worker"
    ErrorQueue = "error"
    NumberOfWorkerThreads = 1
    MaxRetries = 5
    IsTransactional = false
    PurgeOnStartup = false

component IMessageSerializer, MessageSerializer
component IBuilder, Builder

 

2. Program initialization:

var container = new WindsorContainer();

BooReader.Read(container, "nServiceBus.boo");

container.Register(SagasAndMessageHandlers.From(typeof(EventMessageHandler).Assembly));

var bus = container.Resolve<IBus>();

bus.Start();

 

That’s all. Now you can start send/receive messages.

For my taste this is much more readable and maintainable than traditional NServiceBus configuration. Less code, no XML, much cleaner, container friendly.

To make this work you have need for adapter class itself. His responsibility is to forward IBuilder.Build<T> calls to Castle’s Resolve<T> methods. Also, a small helper class that will register Sagas and MessageHandlers in container. Here it is:

public static class SagasAndMessageHandlers
{
    public static IRegistration[] From(params Assembly[] assemblies)
    {
        var registrations = new List<ComponentRegistration>();
        foreach (var assembly in assemblies)
        {
            var types = assembly.GetTypes();
            foreach (var type in types)
            {
                var implementedInterfaces = type.GetInterfaces();
                foreach (var interf in implementedInterfaces)
                {
                    if (!interf.IsGenericType)
                        continue;
                    var genericArguments = interf.GetGenericArguments();
                    if (genericArguments.Length != 1)
                        continue;

                    if (!typeof(IMessage).IsAssignableFrom(genericArguments[0]))
                        continue;

                    var sagaHandlerType = typeof(ISaga<>).MakeGenericType(genericArguments[0]);
                    if (sagaHandlerType.IsAssignableFrom(interf))
                    {
                        registrations.Add(CreateRegistration(type, sagaHandlerType));
                        registrations.Add(CreateRegistration(type, type));
                    }

                    var messageHandlerType = typeof (IMessageHandler<>).MakeGenericType(genericArguments[0]);
                    if (messageHandlerType.IsAssignableFrom(interf))
                        registrations.Add(CreateRegistration(type, type));
                }
            }
        }
        return registrations.ToArray();
    }

    private static ComponentRegistration CreateRegistration(Type type, Type handlerType)
    {
        string componentName;
        if (type == handlerType)
            componentName = type.FullName;
        else
            componentName = type.FullName + handlerType.FullName;

        return (ComponentRegistration)Component
                                          .For(handlerType)
                                          .ImplementedBy(type)
                                          .LifeStyle.Is(LifestyleType.Transient)
                                          .Named(componentName);
    }
}

 

One thing to notice here, NServiceBus required that a saga to be registered as a saga handler ( ISaga<Message>) and as a Saga class itself. A better way will be to use Castle’s newly added forwarding ability, when a component implementation can be accessed through multiple interfaces all forwarded to component’s instance. Bud I had no time to play with this feature yet, so this duplication will still here some time given the fact that no bugs showed up.

You can download a Visual Studio solution with all code shown here from this place. It contains all infrastructure code and two working sample projects ported from original NServiceBus samples – Pub/Sub & Saga.

Generally, the goal of integration tests is to verify that different application parts are glued well together and interacts as expected. Thus, they are a bit different thing from unit tests that tends to test how a small, separate part is acting. Below are two tests that I can’t classify to be pure integration tests because they touch a sensible part of application/infrastructure configuration like Windsor’s configuration files and NHibernate’s mappings. These simple tests can save a lot of time at very initial development stage when application bits are changed frequently and later, as a guarantee that you’ve not broken something in a recent refactoring.

Can_resolve_all_services_in_container()

Bill Simser wrote some time ago about the first test to be written when using Castle’s Windsor Container. It’s a real gem that let’s you verify if any of services registered in container can be resolved (have all required dependencies). Here is it, a bit improved for skipping verification for generic types, since, at that moment, we don’t know the generic argument for type to be constructed:

[Test]
public void Can_resolve_all_services_in_container()
{
    var container = new WindsorContainer("container.xml");
    foreach (IHandler handler in container.Kernel.GetAssignableHandlers(typeof(object)))
    {
        if (handler.ComponentModel.Service.IsGenericType)
            continue;

        container.Resolve(handler.ComponentModel.Service);
    }
}

Can_compile_NHibernate_mapping_configuration()

This test was sitting for a long time in our codebase, but I’ve seen it recently in this post of David Larebee. I wrote it in times when writing our first mappings and the only one way to verify if you don’t have any faults was to write one of CRUD operations and run the test. But that’s a long process. Shorter response cycle is always better. Here it is:

[Test]
public void Can_compile_NHibernate_mapping_configuration()
{
    ISessionFactory factory =
        new Configuration()
            .Configure()
            .AddAssembly("MyApp.MyDomainAssembly")
            .BuildSessionFactory();

    Assert.IsNotNull(factory);
}

This test suppose that you have HNibernate configuration in your app.config and tries to register all mappings from given assembly file.