Thursday, February 10, 2011

NServiceBus assembly scanning: avoiding unintended consequences

The default startup behavior for a NServiceBus endpoint is to scan all assemblies in the deployment directory for any types it might be interested in, for example, message modules and message handlers. This is really handy, but occasionally it can lead to unintended consequences. Fortunately, the With method has a few overloads and one of them takes a list of assemblies to scan. If you want to prevent loading types from any stray assembly that might make it into your deployment directory, change your initialization code to look like this:

var assemblies = GetType().Assembly
   .GetReferencedAssemblies()
   .Select(n => Assembly.Load(n))
   .ToList();
assemblies.Add(GetType().Assembly);
NServiceBus.Configure.With(assemblies);

This restricts the assembly scanning process to only the assemblies that your endpoint explicitly references. We can extract this code to an extension method so we can use it in other endpoints:

public static IEnumerable<Assembly> ReferencedAssemblies(this Type type)
{
   var assemblies = type.Assembly
      .GetReferencedAssemblies()
      .Select(n => Assembly.Load(n))
      .ToList();
   assemblies.Add(GetType().Assembly);
   return assemblies;
}

Now our endpoint initialization looks like this:

NServiceBus.Configure.With(GetType()
   .ReferencedAssemblies());