Using multiple versions of the same namespace in the same Visual Studio project

I had an issue recently when using the NServiceBus.Testing library (version 2.6.0.1504, which is a bit outdated now, but the problem is still interesting). The NServiceBus.Testing library comes with the popular Rhino Mocks framework built in, so by adding a reference to NServiceBus.Testing you automatically end up with the Rhino.Mocks namespace being populated. Unfortunately, I was already using a later version of the Rhino Mocks framework in my project, so this caused a conflict. I couldn’t just remove the existing Rhino Mocks reference because I was relying on features that were not available in the version included with NServiceBus.Testing, and obviously I needed features from the NServiceBus.Testing library, so I had to find a way for the two to co-exist peacefully.

This is possible using reference aliases. By default, when you add a reference to a project, the namespaces in the reference are added with the global namespace alias. However, you can customise the alias by changing the properties of the reference, like so:

Reference alias

This stops the reference being added to the global namespace alias, which in this case meant that any references to the Rhino.Mocks namespace would resolve (correctly) to the Rhino.Mocks reference, instead of NServiceBus.Testing. When you want to use namespaces from a custom-aliased reference in a class, you need to specify the custom alias along with the extern keyword at the top, and use the alias along with a double colon :: as a prefix in the using import statements to specify where to look for a particular namespace, e.g.

extern alias NServiceBusTest;
...
using NServiceBusTest::NServiceBus.Testing;
using Rhino.Mocks;
...
namespace Tests 
{
    [TestFixture]
    public class TestClass
    {
        private Saga<MySaga> _saga;
        private ISomeDependency _dependency;

        [SetUp]
        public void CreateSaga()
        {
            _dependency = MockRepository.GenerateMock<ISomeDependency>(); // resolves to the actual Rhino Mocks reference
            _saga = Test.Saga<MySaga>(); // comes from the NServiceBus testing framework
        }
    }
}

Job’s a good ‘un.