Prerequisites
Ensure an instance of SQL Server (Version 2016 or above for custom saga finders sample, or Version 2012 or above for other samples) is installed and accessible on localhost
and port 1433
. A Docker image can be used to accomplish this by running docker run -e 'ACCEPT_EULA=Y' -e 'MSSQL_SA_PASSWORD=yourStrong(!)Password' -p 1433:1433 -d mcr.
in a terminal.
Alternatively, change the connection string to point to different SQL Server instance.
At startup each endpoint will create its required SQL assets including databases, tables, and schemas.
The database created by this sample is called SQLServerTruncate
.
Running the project
- Start both the Sender and Receiver projects.
- Press c to send a command, or e to publish an event to the receiver endpoint.
- The receiver endpoint will handle the messages in the matching handler.
Code walk-through
When the endpoint starts up, it runs all startup task instances. In this sample, the TruncateTableAtStartup
class is used to truncate the table if it exists at startup.
public class TruncateTableStartupFeature : Feature
{
public TruncateTableStartupFeature()
{
EnableByDefault();
}
protected override void Setup(FeatureConfigurationContext context)
{
context.RegisterStartupTask(new Truncate(context.Settings.Get<TransportInfrastructure>()));
}
class Truncate : FeatureStartupTask
{
readonly TransportInfrastructure transportInfrastructure;
public Truncate(TransportInfrastructure transportInfrastructure)
{
this.transportInfrastructure = transportInfrastructure;
}
protected override async Task OnStart(IMessageSession session)
{
var endpoint = new NServiceBus.Routing.EndpointInstance("Samples.SqlServer.TruncateReceiver");
// for SqlExpress use Data Source=.\SqlExpress;Initial Catalog=SQLServerTruncate;Integrated Security=True;Max Pool Size=100;Encrypt=false
var connectionString = @"Server=localhost,1433;Initial Catalog=SQLServerTruncate;User Id=SA;Password=yourStrong(!)Password;Max Pool Size=100;Encrypt=false";
await SqlHelper.TruncateMessageTable(connectionString, transportInfrastructure.ToTransportAddress(LogicalAddress.CreateRemoteAddress(endpoint)));
}
protected override Task OnStop(IMessageSession session)
{
return Task.CompletedTask;
}
}
}
Configure the SQL Server transport
var transport = endpointConfiguration.UseTransport<SqlServerTransport>();
// for SqlExpress use Data Source=.\SqlExpress;Initial Catalog=SQLServerTruncate;Integrated Security=True;Max Pool Size=100;Encrypt=false
var connectionString = @"Server=localhost,1433;Initial Catalog=SQLServerTruncate;User Id=SA;Password=yourStrong(!)Password;Max Pool Size=100;Encrypt=false";
transport.ConnectionString(connectionString);
transport.Routing().RouteToEndpoint(typeof(MyCommand), "Samples.SqlServer.TruncateReceiver");