Upgrade Version 4 to 5

Component: NServiceBus

Upgrading a major dependency like NServiceBus requires careful planning, see the general recommendations article to learn more about the optimal upgrade process.

Move to .NET 4.5

In Version 5 the minimum .NET version for NServiceBus is .NET 4.5.

**This means consumers need to update all projects (that reference NServiceBus) to be .NET 4.5 before updating to NServiceBus Version 5. **

Note that smaller changes are easier to verify, as such it is recommended to update to .NET 4.5 and perform a full migration to production before updating to NServiceBus Version 5.

https://github.com/Particular/NServiceBus/issues/2078

Interfaces assembly and NuGet deprecated

The NServiceBus interfaces dll was created to allow people to have a smaller dependency when creating a messages assembly. With the introduction of message conventions that is no longer required. As such NServiceBus.dll will be merged into NServiceBus.Core.dll. Also the NServiceBus.Interfaces NuGet will be deprecated.

https://github.com/Particular/NServiceBus/issues/2113

If using NuGet packages

No extra work should be required. A normal NuGet update should result in no NServiceBus.Interfaces NuGet being used and a Version 5 version of the NServiceBus NuGet being used. This is achieved through some NuGet sleight of hand.

If for some reason this sleight of hand fails then manually remove usages of the NServiceBus.Interfaces NuGet and ensure the Version 5 version of the NServiceBus NuGet is used.

If using manual references

  • Remove all references to NServiceBus.dll
  • Update all references of NServiceBus.Core.dll to Version 5

Reflection

Reflection calls that makes assumptions on the assembly name of NServiceBus.dll will need to be updated and re-tested.

Binding Redirects

Any binding redirects pointing to NServiceBus.dll should be removed.

Use of marker interfaces and attributes from NServiceBus.Interfaces.dll

The following have been moved into NServiceBus.Core.dll (part of the NServiceBus NuGet)

  • IMessage
  • IEvent
  • ICommand
  • ExpressAttribute
  • DataBusProperty<T> and IDataBusProperty
  • TimeToBeReceivedAttribute
  • WireEncryptedString
  • ExpressAttribute

So if these markers are still required they can be referenced via NServiceBus.Core.dll.

If "no reference" is required the equivalent conventions can be used instead.

5.x NServiceBus
Edit
var conventions = busConfiguration.Conventions();
conventions.DefiningCommandsAs(
    type =>
    {
        return type.Namespace != null &&
               type.Namespace == "MyNamespace" &&
               type.Namespace.EndsWith("Commands");
    });
conventions.DefiningEventsAs(
    type =>
    {
        return type.Namespace != null &&
               type.Namespace == "MyNamespace" &&
               type.Namespace.EndsWith("Events");
    });
conventions.DefiningMessagesAs(
    type =>
    {
        return type.Namespace != null &&
               type.Namespace == "Messages";
    });
conventions.DefiningDataBusPropertiesAs(
    property =>
    {
        return property.Name.EndsWith("DataBus");
    });
conventions.DefiningExpressMessagesAs(
    type =>
    {
        return type.Name.EndsWith("Express");
    });
conventions.DefiningTimeToBeReceivedAs(
    type =>
    {
        if (type.Name.EndsWith("Expires"))
        {
            return TimeSpan.FromSeconds(30);
        }
        return TimeSpan.MaxValue;
    });
4.x NServiceBus
Edit
// NOTE: When self hosting, '.DefiningXXXAs()' has to be before '.UnicastBus()',
// otherwise it will result in:
// 'InvalidOperationException: "No destination specified for message(s): MessageTypeName"
configure.DefaultBuilder();
configure.DefiningCommandsAs(
    type =>
    {
        return type.Namespace == "MyNamespace" &&
               type.Namespace.EndsWith("Commands");
    });
configure.DefiningEventsAs(
    type =>
    {
        return type.Namespace == "MyNamespace" &&
               type.Namespace.EndsWith("Events");
    });
configure.DefiningMessagesAs(
    type =>
    {
        return type.Namespace == "Messages";
    });
configure.DefiningDataBusPropertiesAs(
    property =>
    {
        return property.Name.EndsWith("DataBus");
    });
configure.DefiningExpressMessagesAs(
    type =>
    {
        return type.Name.EndsWith("Express");
    });
configure.DefiningTimeToBeReceivedAs(
    type =>
    {
        if (type.Name.EndsWith("Expires"))
        {
            return TimeSpan.FromSeconds(30);
        }
        return TimeSpan.MaxValue;
    });

Configure API

The configuration API has been modified to fix several bugs related to method invocation order. The new API takes a Action that configures a ConfigurationBuilder.

5.x NServiceBus
Edit
busConfiguration.AssembliesToScan(AllAssemblies.Except("NotThis.dll"));
var conventions = busConfiguration.Conventions();
conventions.DefiningEventsAs(
    type =>
    {
        return type.Name.EndsWith("Event");
    });
busConfiguration.EndpointName("MyEndpointName");
4.x NServiceBus
Edit
var configure = Configure.With(AllAssemblies.Except("NotThis.dll"));
configure.DefaultBuilder();
configure.DefineEndpointName("MyEndpointName");
configure.DefiningEventsAs(
    type =>
    {
        return type.Name.EndsWith("Event");
    });

https://github.com/Particular/NServiceBus/issues/356

Transport definitions for UseTransport have been renamed

When using UseTransport<T> the transport definition types have been suffixed with Transport.

5.x NServiceBus
Edit
// Choose one of the following

busConfiguration.UseTransport<MsmqTransport>();

busConfiguration.UseTransport<RabbitMQTransport>();

busConfiguration.UseTransport<SqlServerTransport>();

busConfiguration.UseTransport<AzureStorageQueueTransport>();

busConfiguration.UseTransport<AzureServiceBusTransport>();
4.x NServiceBus
Edit
// Choose one of the following

configure.UseTransport<Msmq>();

configure.UseTransport<RabbitMQ>();

configure.UseTransport<SqlServer>();

configure.UseTransport<AzureStorageQueue>();

configure.UseTransport<AzureServiceBus>();

Logging

NServiceBus now has sensible defaults for logging built in.

NLog and Log4net integration have been extracted to external NuGet packages. For more information see logging-in-nservicebus

Obsolete sending and publishing batches of messages together in a single call

As part of Version 5 batch sending of messages has been removed.

So previous code that looks like this

bus.Send(new Message1(), new Message2(), new Message3());

Should be changed to this

bus.Send(new Message1());
bus.Send(new Message2());
bus.Send(new Message3());

The full list of Replacements is below

Old MethodReplacement Method
Publish(T[] messages);Publish(T message);
SendLocal(object[] messages);SendLocal(object message);
Send(object[] messages);Send(object message);
Send(string destination, object[] messages);Send(string destination, object message);
Send(Address address, object[] messages);Send(Address address, object message);
Send(string destination, string correlationId, object[] messages);Send(string destination, string correlationId, object message);
SendToSites(IEnumerable siteKeys, object[] messages);SendToSites(IEnumerable siteKeys, object message);
Defer(TimeSpan delay, object[] messages);Defer(TimeSpan delay, object message);
Defer(DateTime processAt, object[] messages);Defer(DateTime processAt, object message);
Reply(object[] messages);Reply(object message);

https://github.com/Particular/NServiceBus/issues/1346

InMemory removal

Due to significant confusion about the usage of this API it has been removed from Version 5. People using this API should either

  • Move over to doing a normal Publish or
  • Call the required methods explicitly

https://github.com/Particular/NServiceBus/issues/2084

Remove IMessageModule in favor of IManageUnitsOfWork

As part of Version 4 an improved abstraction (IManageUnitsOfWork) was introduced and IMessageModule was deprecated.

In Version 5 this changed is being completed with the remove of IMessageModule.

Uses of IMessageModule should be replaced with IManageUnitsOfWork.

https://github.com/Particular/NServiceBus/issues/2191

Remove Bus.CreateInstance

In Version 4 messages could be created with two approaches. In Version 5 the same can be achieved using only one of those approaches.

5.x NServiceBus
Edit
Bus.Publish<MyInterfaceMessage>(o =>
{
    o.OrderNumber = 1234;
});
4.x NServiceBus
Edit
var message = Bus.CreateInstance<MyInterfaceMessage>(
    action: interfaceMessage =>
    {
        interfaceMessage.OrderNumber = 1234;
    });
Bus.Publish(message);

Bus.Publish<MyInterfaceMessage>(
    messageConstructor: interfaceMessage =>
    {
        interfaceMessage.OrderNumber = 1234;
    });

How to publish an interface event using reflection

In some contexts it may not be possible to invoke the generic IBus.Publish(). For example if when receiving a message via a non typed webservice. In these case use IMessageCreator to construct the instance.

IMessageCreator can be accessed via the container, the recommended way to do this is to passes it into the constructor of the class (eg Handler, Saga, IWantToRunWhenBusStartsAndStops etc).

5.x NServiceBus
Edit
// This type would be derived from some other runtime information
var messageType = typeof(MyInterfaceMessage);

var instance = messageCreator.CreateInstance(messageType);

// use reflection to set properties on the constructed instance

Bus.Publish(instance);

https://github.com/Particular/NServiceBus/issues/2244

Pull Gateway out of the core

The Gateway has been move to a separate NServiceBus.Gateway NuGet.

https://github.com/Particular/NServiceBus/issues/1603

Update to RavenDB 2.5

Version 5 has been updated to use Raven 2.5.

The standard approach for updating RavenDB is to update the server first and then, later, update the client. The benefit of this approach is the risk is split and each part can be verified individually.

While this approach can be taken when updating to RavenDB 2.5 there are known issues when talking from a Raven 2.0 client to a RavenDB 2.5 server. However this issue only occurs in rare circumstances, so it is the decision of the consumer to decide which approach is best for their scenario.

See Using RavenDb in NServiceBus for additional details on upgrading from Raven 2.0 to 2.5.

RavenDB is split from the core

To allow a more regular cadence of RavenDB updates and it isolate those changes the RavenDB integration for NServiceBus has been extracted to its own NuGet.

To move over to this NuGet after updating to Version 5:

https://github.com/Particular/NServiceBus/issues/1605

1. Install the NServiceBus.RavenDB NuGet package

Install-Package NServiceBus.RavenDB

2. Use the new configuration API

5.x NServiceBus
Edit
var documentStore = new DocumentStore
{
    Url = "http://localhost:8080",
    DefaultDatabase = "MyDatabase",
};

documentStore.Initialize();

var busConfiguration = new BusConfiguration();

var persistence = busConfiguration.UsePersistence<RavenDBPersistence>();
persistence.SetDefaultDocumentStore(documentStore);
4.x NServiceBus
Edit
configure.RavenPersistence("http://localhost:8080", "MyDatabase");

Pull the distributor out of the core

The Distributor feature has been extracted into its own NuGet. More details on this change: https://github.com/Particular/NServiceBus/issues/1604

To move over to this NuGet after updating to Version 5:

  1. Install the NServiceBus.Distributor.MSMQ NuGet package
  2. Replace old profile names with their new counterparts:
Old ProfileNew Profile
NServiceBus.DistributorNServiceBus.MsmqDistributor
NServiceBus.MasterNServiceBus.MsmqMaster
NServiceBus.WorkerNServiceBus.MsmqWorker

Obsoleted the IWantToRunBeforeConfiguration API since its no longer needed

Replacement is to either use a INeedInitalization or go with a Feature where a Default(s=>..) can be setup in the constructor of the feature.

https://github.com/Particular/NServiceBus/pull/2180

Remove UnicastBus.Start(Action)

The startupAction parameter of UnicastBus.Start executed the action immediately before the actual start of the bus. This provided no real value since a consumer can execute said action prior to calling Start.

5.x NServiceBus
Edit
var startableBus = Bus.Create(new BusConfiguration());
MyCustomAction();
startableBus.Start();
4.x NServiceBus
Edit
configure.UnicastBus();
var startableBus = configure.CreateBus();
startableBus.Start(
    startupAction: () =>
    {
        MyCustomAction();
    });

https://github.com/Particular/NServiceBus/issues/2168

Remove ForInstallationOn, Windows and IEnvironment

This API has been simplified.

5.x NServiceBus
Edit
busConfiguration.EnableInstallers();
// this will run the installers
Bus.Create(busConfiguration);
4.x NServiceBus
Edit
var configure = Configure.With();
configure.UnicastBus();
var startableBus = configure.CreateBus();
startableBus.Start(
    startupAction: () =>
    {
        configure.ForInstallationOn<Windows>().Install();
    });

https://github.com/Particular/NServiceBus/issues/2167

Make Scheduler API instance based

5.x NServiceBus
Edit
public class ScheduleMyTasks :
    IWantToRunWhenBusStartsAndStops
{
    IBus bus;
    Schedule schedule;

    public ScheduleMyTasks(IBus bus, Schedule schedule)
    {
        this.bus = bus;
        this.schedule = schedule;
    }

    public void Start()
    {
        // To send a message every 5 minutes
        schedule.Every(
            timeSpan: TimeSpan.FromMinutes(5),
            task: () =>
            {
                var message = new MyMessage();
                bus.SendLocal(message);
            });

        // Name a schedule task and invoke it every 5 minutes
        schedule.Every(
            timeSpan: TimeSpan.FromMinutes(5),
            name: "Task name",
            task: () =>
            {
                var message = new MyMessage();
                bus.SendLocal(message);
            });
    }

    public void Stop()
    {
    }
}
4.x NServiceBus
Edit
public class ScheduleMyTasks :
    IWantToRunWhenBusStartsAndStops
{
    IBus bus;

    public ScheduleMyTasks(IBus bus)
    {
        this.bus = bus;
    }

    public void Start()
    {
        // To send a message every 5 minutes
        Schedule.Every(TimeSpan.FromMinutes(5))
            .Action(() =>
            {
                var myMessage = new MyMessage();
                bus.SendLocal(myMessage);
            });

        // Name a schedule task and invoke it every 5 minutes
        Schedule.Every(TimeSpan.FromMinutes(5))
            .Action("Task name", () =>
            {
                var myMessage = new MyMessage();
                bus.SendLocal(myMessage);
            });
    }

    public void Stop()
    {
    }
}

https://github.com/Particular/NServiceBus/pull/2192

Make ConfigureHowToFindSaga abstract

Many bugs are caused by this method not being overridden. As such it will now be abstract.

5.x NServiceBus
Edit
public class MySaga :
    Saga<MySagaData>,
    IAmStartedByMessages<Message1>,
    IHandleMessages<Message2>
{
    protected override void ConfigureHowToFindSaga(SagaPropertyMapper<MySagaData> mapper)
    {
        mapper.ConfigureMapping<Message2>(message => message.SomeId)
            .ToSaga(sagaData => sagaData.SomeId);
    }
4.x NServiceBus
Edit
public class MySaga :
    Saga<MySagaData>,
    IAmStartedByMessages<Message1>,
    IHandleMessages<Message2>
{
    public override void ConfigureHowToFindSaga()
    {
        ConfigureMapping<Message2>(message => message.SomeId)
            .ToSaga(sagaData => sagaData.SomeId);
    }

https://github.com/Particular/NServiceBus/issues/2137

Standardize extension methods to configure persistences

In the interest of keeping the API consistent a standard approach for choosing and configuring persistences has been applied.

5.x NServiceBus
Edit
// Configure to use InMemory for all persistence types
busConfiguration.UsePersistence<InMemoryPersistence>();

// Configure to use InMemory for specific persistence types
busConfiguration.UsePersistence<InMemoryPersistence>()
    .For(
        Storage.Sagas,
        Storage.Subscriptions);

// Configure to use NHibernate for all persistence types
busConfiguration.UsePersistence<NHibernatePersistence>();

// Configure to use NHibernate for specific persistence types
busConfiguration.UsePersistence<NHibernatePersistence>()
    .For(
        Storage.Sagas,
        Storage.Subscriptions);

// Configure to use RavenDB for all persistence types
busConfiguration.UsePersistence<RavenDBPersistence>();

// Configure to use RavenDB for specific persistence types
busConfiguration.UsePersistence<RavenDBPersistence>()
    .For(
        Storage.Sagas,
        Storage.Subscriptions);
4.x NServiceBus
Edit
// Configure to use InMemory
configure.InMemorySagaPersister();
configure.UseInMemoryTimeoutPersister();
configure.InMemorySubscriptionStorage();
configure.RunGatewayWithInMemoryPersistence();
configure.UseInMemoryGatewayDeduplication();

// Configure to use NHibernate
configure.UseNHibernateSagaPersister();
configure.UseNHibernateTimeoutPersister();
configure.UseNHibernateSubscriptionPersister();
configure.UseNHibernateGatewayPersister();
configure.UseNHibernateGatewayDeduplication();

// Configure to use RavenDB for everything
configure.RavenPersistence();

// Configure to use RavenDB
configure.RavenSagaPersister();
configure.UseRavenTimeoutPersister();
configure.RavenSubscriptionStorage();
configure.RunGatewayWithRavenPersistence();
configure.UseNHibernateGatewayDeduplication();

https://github.com/Particular/NServiceBus/issues/2102

Obsolete the SerializationSettings properties WrapSingleMessages and DontWrapSingleMessages

In Version 5 multi-message sends is removed. So wrapping messages is no longer required. Usages of these settings should be removed.

https://github.com/Particular/NServiceBus/issues/2104

Change IMessageSerializer.Serialize to take a single message

In Version 5 multi-message sends is removed. So serialization of an array of messages is no longer required.

Implementations of IMessageSerializer should change to take a single object.

Usages of IMessageSerializer should no longer pass in an array of objects.

https://github.com/Particular/NServiceBus/issues/2105

Replace ISaga with non generic base class Saga

Use abstract classes Saga<T> (for generic access to the saga data) or Saga (for non-generic access to the saga data) instead.

This should only effect scenarios that are leveraging more advanced NServiceBus extensions. This is because in Version 4 it was not possible to use ISaga to create a saga.

https://github.com/Particular/NServiceBus/issues/2095

Remove Bus.Subscribe Predicate overloads

Instead create a Handler that does this filtering logic and then, optionally, calls DoNotContinueDispatchingCurrentMessageToHandlers. This Handler should be ordered to run before other handlers.

https://github.com/Particular/NServiceBus/issues/2088

Remove this.Bus() extension method for IHandleMessages implementations

In Version 4 there was an extension method on IHandleMessages that supplied a static instance of the IBus. This allowed consumers to write this.Bus().Reply(response);.

While this was convenient the tax of allowing static access to an instance of the IBus was too high. As such this extension has been removed.

The replacement is to inject an instance of IBus as a constructor parameter and then assign that to a field for later use.

5.x NServiceBus
Edit
public class MyHandler :
    IHandleMessages<MyMessage>
{
    IBus bus;

    public MyHandler(IBus bus)
    {
        this.bus = bus;
    }

    public void Handle(MyMessage message)
    {
        var otherMessage = new OtherMessage();
        bus.Reply(otherMessage);
    }
}
4.x NServiceBus
Edit
public class MyHandler :
    IHandleMessages<MyMessage>
{
    public void Handle(MyMessage message)
    {
        var otherMessage = new OtherMessage();
        this.Bus().Reply(otherMessage);
    }
}

https://github.com/Particular/NServiceBus/issues/2082

Remove .RunCustomAction()

5.x NServiceBus
Edit
var startableBus = Bus.Create(new BusConfiguration());
MyCustomAction();
startableBus.Start();
4.x NServiceBus
Edit
var configure = Configure.With();
configure.UnicastBus();
configure.RunCustomAction(MyCustomAction);
var startableBus = configure.CreateBus();
startableBus.Start();

https://github.com/Particular/NServiceBus/issues/1366

Moved DefineCriticalErrorAction to be a ConfigurationBuilder extension

5.x NServiceBus
Edit
// Configuring how NServiceBus handles critical errors
busConfiguration.DefineCriticalErrorAction(
    (message, exception) =>
    {
        var output = $"Critical exception: '{message}'";
        log.Error(output, exception);
        // Perhaps end the process??
    });
4.x NServiceBus
Edit
// Configuring how NServiceBus handles critical errors
var configure = Configure.With();
configure.DefineCriticalErrorAction(
    (message, exception) =>
    {
        var output = $"Critical exception: '{message}'";
        log.Error(output, exception);
        // Perhaps end the process?
    });

https://github.com/Particular/NServiceBus/issues/2254

Moved FileShareDataBus to a ConfigurationBuilder extension

5.x NServiceBus
Edit
var dataBus = busConfiguration.UseDataBus<FileShareDataBus>();
dataBus.BasePath(databusPath);
4.x NServiceBus
Edit
var configure = Configure.With();
configure.FileShareDataBus(databusPath);

https://github.com/Particular/NServiceBus/issues/2257

Moved PurgeOnStartup to be a ConfigurationBuilder extension

5.x NServiceBus
Edit
busConfiguration.PurgeOnStartup(true);
4.x NServiceBus
Edit
var configure = Configure.With();
configure.PurgeOnStartup(true);

https://github.com/Particular/NServiceBus/issues/2257

Moved License configuration API to be a ConfigurationBuilder extension

5.x NServiceBus
Edit
busConfiguration.LicensePath("PathToLicense");
// or
busConfiguration.License("YourCustomLicenseText");
4.x NServiceBus
Edit
configure.LicensePath("PathToLicense");
// or
configure.License("YourCustomLicenseText");

https://github.com/Particular/NServiceBus/issues/2278

Moved EncryptionService to be a ConfigurationBuilder extension

RijndaelEncryption

5.x NServiceBus
Edit
busConfiguration.RijndaelEncryptionService();
4.x NServiceBus
Edit
var configure = Configure.With();
configure.RijndaelEncryptionService();

https://github.com/Particular/NServiceBus/issues/2265

Custom IEncryptionService

4.x NServiceBus
Edit
// where EncryptionService implements IEncryptionService
var configure = Configure.With();
var components = configure.Configurer;
components.RegisterSingleton<IEncryptionService>(new EncryptionService());

https://github.com/Particular/NServiceBus/pull/2270

Moved Transaction config to ConfigurationBuilder

5.x NServiceBus
Edit
// Enable
busConfiguration.Transactions().Enable();

// Disable
busConfiguration.Transactions().Disable();
4.x NServiceBus
Edit
// Enable
Configure.Transactions.Enable();

// Disable
Configure.Transactions.Disable();

https://github.com/Particular/NServiceBus/pull/2283

Moved static Endpoint config to ConfigurationBuilder

5.x NServiceBus
Edit
// SendOnly
Bus.CreateSendOnly(busConfiguration);

// AsVolatile
var transactions = busConfiguration.Transactions();
transactions.Disable();
busConfiguration.DisableDurableMessages();
busConfiguration.UsePersistence<InMemoryPersistence>();

// DisableDurableMessages
busConfiguration.DisableDurableMessages();

// EnableDurableMessages
busConfiguration.EnableDurableMessages();
4.x NServiceBus
Edit
var endpoint = Configure.Endpoint;
endpoint.AsSendOnly();
endpoint.AsVolatile();
endpoint.Advanced(settings => settings.DisableDurableMessages());
endpoint.Advanced(settings => settings.EnableDurableMessages());

Moved Performance monitoring and SLA to ConfigurationBuilder

5.x NServiceBus
Edit
busConfiguration.EnableSLAPerformanceCounter();
// or
busConfiguration.EnableSLAPerformanceCounter(TimeSpan.FromMinutes(3));
4.x NServiceBus
Edit
var configure = Configure.With();
configure.EnablePerformanceCounters();
configure.SetEndpointSLA(TimeSpan.FromMinutes(3));

https://github.com/Particular/NServiceBus/issues/2284

Configure.Instance

Configure.Instance has been deprecated. The alternatives for usage include

At configuration time

Some configuration APIs previously required access to an instance of Configure via Configure.Instance. For example IWantToRunBeforeConfigurationIsFinalized and IWantToRunWhenConfigurationIsComplete. These interfaces have been modified in Version 5 so an instance of Configure is passed in.

To resolve IBuilder

In Version 4 it was possible to use Configure.Instance to get access to an instance of IBuilder. Instead of using IBuilder to access other run time instances that exist in the container, resolve them via dependency injection. Another alternative to using IBuilder is to configure NServiceBus to use a custom container instance. After starting the bus this instance can be used to resolve instances. Each of the container integrations have an associated sample that show how to pass in a custom instance of that container.

To statically resolve IBus

One common use of Configure.Instance in Version 4 was to access an instance of IBus in the static context, i.e. with this code Configure.Instance.Builder.Build<IBus>(). It is recommended to avoid using the static context and instead construct the instances via the container. For example to inject IBus add a constructor parameter of the type IBus and store that in a field for when it is needed.

If the class cannot be constructed though dependency injection store the instance of IBus returned from Bus.Create(busConfiguration).Start() in a static variable and access it in the global context.

Static resolution via IWantToRunWhenBusStartsAndStops

Access to IBuilder and IBus via Bus.Create(busConfiguration).Start() will not be available when using the NServiceBus host or plugging into NServiceBus in a generic library. Work around this by capturing both IBuilder and IBus via a IWantToRunWhenBusStartsAndStops and storing them statically.

5.x NServiceBus
Edit
public class BusInstance :
    IWantToRunWhenBusStartsAndStops
{
    public BusInstance(IBus bus, IBuilder builder)
    {
        Bus = bus;
        Builder = builder;
    }

    public static IBuilder Builder;
    public static IBus Bus;

Note that this approach should only be considered when resolving the components via the container is not an option.

Moved SendOnly mode to ConfigurationBuilder

5.x NServiceBus
Edit
var sendOnlyBus = Bus.CreateSendOnly(busConfiguration);
4.x NServiceBus
Edit
configure.DefaultBuilder();
// Other config
configure.UnicastBus();
var bus = configure.SendOnly();

https://github.com/Particular/NServiceBus/pull/2295

Removed EndpointName to ConfigurationBuilder and removed Func overload

5.x NServiceBus
Edit
busConfiguration.EndpointName("MyEndpoint");
4.x NServiceBus
Edit
// To customize the endpoint name via code using the DefineEndpointName method,
// it is important to call it first, right after the With() configuration entry point.
configure.DefineEndpointName("MyEndpoint");

https://github.com/Particular/NServiceBus/pull/2275

Moved DoNotCreateQueues to a ConfigurationBuilder extension

5.x NServiceBus
Edit
busConfiguration.DoNotCreateQueues();
4.x NServiceBus
Edit
var configure = Configure.With();
configure.DoNotCreateQueues();

https://github.com/Particular/NServiceBus/issues/2263

Remove RunHandlersUnderIncomingPrincipal

The RunHandlersUnderIncomingPrincipal method has been removed.

This API was frequently assumed to be a security feature. In reality this API exposes the username from the message sending code to executing handlers. It does this by setting Thread.CurrentPrincipal to a fake principal containing the username of the user who sent the message. It extracts this username from the message headers. The handler code is free use use Thread.CurrentPrincipal or to ignore. It does not add any security or perform any true impersonation.

To re-enable this feature a message mutator can be used mutator.

5.x NServiceBus
Edit
public class PrincipalMutator :
    IMutateIncomingTransportMessages
{
    public void MutateIncoming(TransportMessage message)
    {
        var headers = message.Headers;
        var windowsIdentityName = headers[Headers.WindowsIdentityName];
        var identity = new GenericIdentity(windowsIdentityName);
        var principal = new GenericPrincipal(identity, new string[0]);
        Thread.CurrentPrincipal = principal;
    }
}
4.x NServiceBus
Edit
var unicastBus = configure.UnicastBus();
unicastBus.RunHandlersUnderIncomingPrincipal(true);

Another option is to use a custom header as illustrated in Appending username using headers sample.

INeedToInstallInfrastructure

The interface INeedToInstallInfrastructure<T> has been removed. Use PowerShell commandlets as an alternative.


Last modified