diff --git a/Snippets/Core/Core_10/BasicUsageOfIBus.cs b/Snippets/Core/Core_10/BasicUsageOfIBus.cs index 8b374f683d1..0a50952fa1a 100644 --- a/Snippets/Core/Core_10/BasicUsageOfIBus.cs +++ b/Snippets/Core/Core_10/BasicUsageOfIBus.cs @@ -5,13 +5,12 @@ class BasicUsageOfIBus { - async Task Send(EndpointConfiguration endpointConfiguration) + async Task Send(IMessageSession messageSession) { #region BasicSend - var endpointInstance = await Endpoint.Start(endpointConfiguration); var message = new MyMessage(); - await endpointInstance.Send(message); + await messageSession.Send(message); #endregion } @@ -30,86 +29,86 @@ public Task Handle(MyMessage message, IMessageHandlerContext context) #endregion - async Task SetDestination(IEndpointInstance endpoint) + async Task SetDestination(IMessageSession messageSession) { #region BasicSendSetDestination var options = new SendOptions(); options.SetDestination("MyDestination"); - await endpoint.Send(new MyMessage(), options); + await messageSession.Send(new MyMessage(), options); #endregion } - async Task SpecificInstance(IEndpointInstance endpoint) + async Task SpecificInstance(IMessageSession messageSession) { #region BasicSendSpecificInstance var options = new SendOptions(); options.RouteToSpecificInstance("MyInstance"); var message = new MyMessage(); - await endpoint.Send(message, options); + await messageSession.Send(message, options); #endregion } - async Task ThisEndpoint(IEndpointInstance endpoint) + async Task ThisEndpoint(IMessageSession messageSession) { #region BasicSendToAnyInstance var options = new SendOptions(); options.RouteToThisEndpoint(); - await endpoint.Send(new MyMessage(), options); + await messageSession.Send(new MyMessage(), options); // or - await endpoint.SendLocal(new MyMessage()); + await messageSession.SendLocal(new MyMessage()); #endregion } - async Task ThisInstance(IEndpointInstance endpoint) + async Task ThisInstance(IMessageSession messageSession) { #region BasicSendToThisInstance var options = new SendOptions(); options.RouteToThisInstance(); var message = new MyMessage(); - await endpoint.Send(message, options); + await messageSession.Send(message, options); #endregion } - async Task SendReplyToThisInstance(IEndpointInstance endpoint) + async Task SendReplyToThisInstance(IMessageSession messageSession) { #region BasicSendReplyToThisInstance var options = new SendOptions(); options.RouteReplyToThisInstance(); var message = new MyMessage(); - await endpoint.Send(message, options); + await messageSession.Send(message, options); #endregion } - async Task SendReplyToAnyInstance(IEndpointInstance endpoint) + async Task SendReplyToAnyInstance(IMessageSession messageSession) { #region BasicSendReplyToAnyInstance var options = new SendOptions(); options.RouteReplyToAnyInstance(); var message = new MyMessage(); - await endpoint.Send(message, options); + await messageSession.Send(message, options); #endregion } - async Task SendReplyTo(IEndpointInstance endpoint) + async Task SendReplyTo(IMessageSession messageSession) { #region BasicSendReplyToDestination var options = new SendOptions(); options.RouteReplyTo("MyDestination"); var message = new MyMessage(); - await endpoint.Send(message, options); + await messageSession.Send(message, options); #endregion } diff --git a/Snippets/Core/Core_10/Container/ExternallyManaged.cs b/Snippets/Core/Core_10/Container/ExternallyManaged.cs index 8a70ef31040..6c588375532 100644 --- a/Snippets/Core/Core_10/Container/ExternallyManaged.cs +++ b/Snippets/Core/Core_10/Container/ExternallyManaged.cs @@ -10,6 +10,7 @@ public class ExternallyManaged { async Task Usage(EndpointConfiguration endpointConfiguration) { +#pragma warning disable CS0618 // Type or member is obsolete #region ExternalPrepare IServiceCollection serviceCollection = new ServiceCollection(); @@ -25,5 +26,6 @@ async Task Usage(EndpointConfiguration endpointConfiguration) var startedEndpoint = await startableEndpoint.Start(builder); #endregion +#pragma warning restore CS0618 // Type or member is obsolete } } \ No newline at end of file diff --git a/Snippets/Core/Core_10/Container/Usage.cs b/Snippets/Core/Core_10/Container/Usage.cs index 57bdb1ed640..4e989312d3b 100644 --- a/Snippets/Core/Core_10/Container/Usage.cs +++ b/Snippets/Core/Core_10/Container/Usage.cs @@ -5,6 +5,7 @@ class Usage { +#pragma warning disable CS0618 // Type or member is obsolete void InstancePerCall(EndpointConfiguration endpointConfiguration) { #region InstancePerCall @@ -82,4 +83,5 @@ void DelegateSingleInstance(EndpointConfiguration endpointConfiguration) #endregion } +#pragma warning restore CS0618 // Type or member is obsolete } \ No newline at end of file diff --git a/Snippets/Core/Core_10/Core_10.csproj b/Snippets/Core/Core_10/Core_10.csproj index ff73df3acce..f74bfaca474 100644 --- a/Snippets/Core/Core_10/Core_10.csproj +++ b/Snippets/Core/Core_10/Core_10.csproj @@ -10,9 +10,9 @@ - + - + diff --git a/Snippets/Core/Core_10/DelayedDelivery/DeferForDateTime.cs b/Snippets/Core/Core_10/DelayedDelivery/DeferForDateTime.cs index 0763fc34d5f..7621566e641 100644 --- a/Snippets/Core/Core_10/DelayedDelivery/DeferForDateTime.cs +++ b/Snippets/Core/Core_10/DelayedDelivery/DeferForDateTime.cs @@ -6,7 +6,7 @@ namespace Core.DelayedDelivery; class DeferForDateTime { - async Task SendDelayedMessage(IEndpointInstance endpoint, IMessageHandlerContext handlerContext) + async Task SendDelayedMessage(IMessageSession messageSession, IMessageHandlerContext handlerContext) { #region delayed-delivery-datetime var options = new SendOptions(); @@ -14,7 +14,7 @@ async Task SendDelayedMessage(IEndpointInstance endpoint, IMessageHandlerContext await handlerContext.Send(new MessageToBeSentLater(), options); // OR - await endpoint.Send(new MessageToBeSentLater(), options, handlerContext.CancellationToken); + await messageSession.Send(new MessageToBeSentLater(), options, handlerContext.CancellationToken); #endregion } diff --git a/Snippets/Core/Core_10/DelayedDelivery/DeferForTimeSpan.cs b/Snippets/Core/Core_10/DelayedDelivery/DeferForTimeSpan.cs index 3e657ff07e1..a4b0e1b8a06 100644 --- a/Snippets/Core/Core_10/DelayedDelivery/DeferForTimeSpan.cs +++ b/Snippets/Core/Core_10/DelayedDelivery/DeferForTimeSpan.cs @@ -6,7 +6,7 @@ class DeferForTimeSpan { - async Task SendDelayedMessage(EndpointConfiguration endpointConfiguration, IEndpointInstance endpoint, IMessageHandlerContext handlerContext) + async Task SendDelayedMessage(EndpointConfiguration endpointConfiguration, IMessageSession messageSession, IMessageHandlerContext handlerContext) { #region configure-persistence-timeout @@ -22,7 +22,7 @@ async Task SendDelayedMessage(EndpointConfiguration endpointConfiguration, IEndp await handlerContext.Send(new MessageToBeSentLater(), sendOptions); // OR - await endpoint.Send(new MessageToBeSentLater(), sendOptions, handlerContext.CancellationToken); + await messageSession.Send(new MessageToBeSentLater(), sendOptions, handlerContext.CancellationToken); #endregion } diff --git a/Snippets/Core/Core_10/Features/FeatureConfiguration.cs b/Snippets/Core/Core_10/Features/FeatureConfiguration.cs index 686553670c5..47592d324c4 100644 --- a/Snippets/Core/Core_10/Features/FeatureConfiguration.cs +++ b/Snippets/Core/Core_10/Features/FeatureConfiguration.cs @@ -30,8 +30,6 @@ async Task EndpointConfiguration(EndpointConfiguration endpointConfiguration) // disable features not in use endpointConfiguration.DisableFeature(); - - var startableEndpoint = await Endpoint.Create(endpointConfiguration); #endregion } diff --git a/Snippets/Core/Core_10/Handlers/ConventionBasedHandlers.cs b/Snippets/Core/Core_10/Handlers/ConventionBasedHandlers.cs new file mode 100644 index 00000000000..c8204b8b0be --- /dev/null +++ b/Snippets/Core/Core_10/Handlers/ConventionBasedHandlers.cs @@ -0,0 +1,116 @@ +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Configuration; +using NServiceBus; + +namespace OuterNS.InnerNS; + +public record MyMessage(); +public record Msg1(); +public record Msg2(); + +#region SimpleConventionBasedHandler + +public class ConventionHandler +{ + public async Task Handle(MyMessage message, IMessageHandlerContext context) + { + // do something with the message data + } +} + +#endregion + +#region ConventionsBasedHandlerExtraParams + +public class ConventionHandlerWithExtraParams +{ + public async Task Handle(MyMessage message, + IMessageHandlerContext context, + DatabaseService database, + CancellationToken cancellationToken) + { + // do something with the message data + } +} + +#endregion + +#region DecoratedConventionHandler + +[Handler] +public class DecoratedConventionHandler +{ + public async Task Handle(MyMessage message, IMessageHandlerContext context) + { + } +} + +#endregion + + +#region ConventionHandlersTldrSample + +[Handler] +public class HandlersByConvention +{ + public async Task Handle(Msg1 message, + IMessageHandlerContext context, + CancellationToken cancellationToken) + { + } + + public static async Task Handle(Msg2 message, + IMessageHandlerContext context, + DatabaseService database, + IConfiguration configuration, + IHttpClientFactory httpClientFactory, + CancellationToken cancellationToken) + { + } +} +#endregion + +public class DatabaseService; + +public class ConventionHandlerRegistration +{ + public static void Setup(EndpointConfiguration endpointConfiguration) + { + #region ConventionHandlerRegistrationWithoutAttribute + + endpointConfiguration.AddHandler(); + + #endregion + + #region ConventionHandlerAddAllFromAssembly + endpointConfiguration.Handlers.SampleProject.AddAll(); + #endregion + + #region ConventionHandlerAllGeneratedAddMethods + + // Add just one handler + endpointConfiguration.Handlers.SampleProject.OuterNS.InnerNS + .AddDecoratedConventionHandler(); + + // Add all handlers or sagas from a namespace… + endpointConfiguration.Handlers.SampleProject.OuterNS.InnerNS.AddAllHandlers(); + endpointConfiguration.Handlers.SampleProject.OuterNS.InnerNS.AddAllSagas(); + endpointConfiguration.Handlers.SampleProject.OuterNS.InnerNS.AddAll(); + // …at any point in the namespace hierarchy + endpointConfiguration.Handlers.SampleProject.OuterNS.AddAllHandlers(); + endpointConfiguration.Handlers.SampleProject.OuterNS.AddAllSagas(); + endpointConfiguration.Handlers.SampleProject.OuterNS.AddAll(); + + // Or add all from an entire assembly + endpointConfiguration.Handlers.SampleProject.AddAllHandlers(); + endpointConfiguration.Handlers.SampleProject.AddAllSagas(); + endpointConfiguration.Handlers.SampleProject.AddAll(); + + #endregion + } +} + +[HandlerRegistryExtensions(EntryPointName = "SampleProject")] +public static partial class RegistrationExtensions; \ No newline at end of file diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterAudit.cs b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterAudit.cs index 0666f9a6e02..34435b74a69 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterAudit.cs +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterAudit.cs @@ -1,4 +1,7 @@ -namespace Core.Headers.Writers; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +namespace Core.Headers.Writers; using System.Threading; using System.Threading.Tasks; @@ -31,10 +34,15 @@ public async Task Write() endpointConfiguration.RegisterMessageMutator(new Mutator()); endpointConfiguration.UseSerialization(); - var endpointInstance = await Endpoint.Start(endpointConfiguration); - await endpointInstance.SendLocal(new MessageToSend()); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + await host.StartAsync(); + var messageSession = host.Services.GetRequiredService(); + + await messageSession.SendLocal(new MessageToSend()); ManualResetEvent.WaitOne(); - await endpointInstance.Stop(); + await host.StopAsync(); } class MessageToSend : diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterAuditAudit.txt b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterAuditAudit.txt index 6acb61ff5cd..b4c4966dcad 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterAuditAudit.txt +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterAuditAudit.txt @@ -1,22 +1,23 @@ Snippet is code generated by HeaderWriterAudit.cs startcode HeaderWriterAuditAudit $.diagnostics.hostdisplayname = MACHINENAME -$.diagnostics.hostid = 7f787fc8e0611a3fab8a93c8767f6639 -$.diagnostics.originating.hostid = 7f787fc8e0611a3fab8a93c8767f6639 +$.diagnostics.hostid = daaf5ebc8d6a51b7b0dccdd8b15c3626 +$.diagnostics.originating.hostid = daaf5ebc8d6a51b7b0dccdd8b15c3626 NServiceBus.ContentType = application/json -NServiceBus.ConversationId = 74c7b4a9-65f5-4c15-b173-b33e015e0c71 -NServiceBus.CorrelationId = 7b89fe9e-14f8-4ee4-be40-b33e015e0c70 +NServiceBus.ConversationId = 5520abbd-7b30-4914-a3d4-b43b016d917e +NServiceBus.CorrelationId = 4ad00d77-6e0d-44cc-bd3e-b43b016d917d NServiceBus.EnclosedMessageTypes = Core.Headers.Writers.MyNamespace.MessageToSend, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null -NServiceBus.MessageId = 7b89fe9e-14f8-4ee4-be40-b33e015e0c70 +NServiceBus.MessageId = 4ad00d77-6e0d-44cc-bd3e-b43b016d917d NServiceBus.MessageIntent = Send +NServiceBus.OpenTelemetry.StartNewTrace = False NServiceBus.OriginatingEndpoint = HeaderWriterAudit NServiceBus.OriginatingMachine = MACHINENAME -NServiceBus.ProcessingEnded = 2025-08-19 23:22:04:600525 Z +NServiceBus.ProcessingEnded = 2026-04-29 22:10:59:647662 Z NServiceBus.ProcessingEndpoint = HeaderWriterAudit NServiceBus.ProcessingMachine = MACHINENAME -NServiceBus.ProcessingStarted = 2025-08-19 23:22:04:600177 Z +NServiceBus.ProcessingStarted = 2026-04-29 22:10:59:639234 Z NServiceBus.ReplyToAddress = HeaderWriterAudit -NServiceBus.TimeSent = 2025-08-19 21:14:29:280127 Z -NServiceBus.Version = 10.0.0 +NServiceBus.TimeSent = 2026-04-29 22:10:59:617241 Z +NServiceBus.Version = 10.2.0 endcode \ No newline at end of file diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterAuditSend.txt b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterAuditSend.txt index f7b8b99c66b..8860ed6496f 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterAuditSend.txt +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterAuditSend.txt @@ -1,22 +1,17 @@ Snippet is code generated by HeaderWriterAudit.cs startcode HeaderWriterAuditSend -$.diagnostics.hostdisplayname = MACHINENAME -$.diagnostics.hostid = 7f787fc8e0611a3fab8a93c8767f6639 -$.diagnostics.originating.hostid = 7f787fc8e0611a3fab8a93c8767f6639 +$.diagnostics.originating.hostid = daaf5ebc8d6a51b7b0dccdd8b15c3626 NServiceBus.ContentType = application/json -NServiceBus.ConversationId = cff7bb7c-0f21-4391-85d7-b33e015fda12 -NServiceBus.CorrelationId = b4eafc54-9d18-4728-92a5-b33e015fda11 +NServiceBus.ConversationId = 5520abbd-7b30-4914-a3d4-b43b016d917e +NServiceBus.CorrelationId = 4ad00d77-6e0d-44cc-bd3e-b43b016d917d NServiceBus.EnclosedMessageTypes = Core.Headers.Writers.MyNamespace.MessageToSend, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null -NServiceBus.MessageId = b4eafc54-9d18-4728-92a5-b33e015fda11 +NServiceBus.MessageId = 4ad00d77-6e0d-44cc-bd3e-b43b016d917d NServiceBus.MessageIntent = Send +NServiceBus.OpenTelemetry.StartNewTrace = False NServiceBus.OriginatingEndpoint = HeaderWriterAudit NServiceBus.OriginatingMachine = MACHINENAME -NServiceBus.ProcessingEnded = 2025-08-19 23:22:04:596308 Z -NServiceBus.ProcessingEndpoint = HeaderWriterAudit -NServiceBus.ProcessingMachine = MACHINENAME -NServiceBus.ProcessingStarted = 2025-08-19 23:22:04:589328 Z NServiceBus.ReplyToAddress = HeaderWriterAudit -NServiceBus.TimeSent = 2025-08-19 21:21:03:208659 Z -NServiceBus.Version = 10.0.0 +NServiceBus.TimeSent = 2026-04-29 22:10:59:617241 Z +NServiceBus.Version = 10.2.0 endcode \ No newline at end of file diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDataBusConvention.cs b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDataBusConvention.cs index 80d69af2faa..3359dd8105c 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDataBusConvention.cs +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDataBusConvention.cs @@ -1,4 +1,7 @@ -namespace Core.Headers.Writers; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +namespace Core.Headers.Writers; using System.Text; using System.Threading; @@ -40,15 +43,19 @@ public async Task Write() }); endpointConfiguration.RegisterMessageMutator(new Mutator()); - var endpointInstance = await Endpoint.Start(endpointConfiguration); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + await host.StartAsync(); + var messageSession = host.Services.GetRequiredService(); var messageToSend = new MessageToSend { LargeProperty1 = new byte[10], LargeProperty2 = new byte[10] }; - await endpointInstance.SendLocal(messageToSend); + await messageSession.SendLocal(messageToSend); ManualResetEvent.WaitOne(); - await endpointInstance.Stop(); + await host.StopAsync(); } class MessageToSend : diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDataBusConvention.txt b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDataBusConvention.txt index d548efde56c..e7fe6663f03 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDataBusConvention.txt +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDataBusConvention.txt @@ -1,16 +1,20 @@ Snippet is code generated by HeaderWriterDataBusConvention.cs startcode HeaderWriterDataBusConvention -$.diagnostics.originating.hostid = 7f787fc8e0611a3fab8a93c8767f6639 +$.diagnostics.originating.hostid = daaf5ebc8d6a51b7b0dccdd8b15c3626 NServiceBus.ContentType = application/json -NServiceBus.ConversationId = 5fd3f849-5262-4eeb-8579-b33e0183a22c -NServiceBus.CorrelationId = eb8acac8-2f4a-40da-a448-b33e0183a22c +NServiceBus.ConversationId = ada01a9b-77b0-4163-99d2-b43b016b72f6 +NServiceBus.CorrelationId = 1c907d5f-fafe-4898-857c-b43b016b72f5 +NServiceBus.DataBus.Core.Headers.Writers.MyNamespace.MessageToSend.LargeProperty1 = 2026-04-29_22/eec27ca0-ef0e-41f3-aeb4-fb47057efb53 +NServiceBus.DataBus.Core.Headers.Writers.MyNamespace.MessageToSend.LargeProperty2 = 2026-04-29_22/b32fc5cc-949a-4e62-87ec-8da83c644d3c +NServiceBus.DataBusConfig.ContentType = application/json NServiceBus.EnclosedMessageTypes = Core.Headers.Writers.MyNamespace.MessageToSend, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null -NServiceBus.MessageId = eb8acac8-2f4a-40da-a448-b33e0183a22c +NServiceBus.MessageId = 1c907d5f-fafe-4898-857c-b43b016b72f5 NServiceBus.MessageIntent = Send +NServiceBus.OpenTelemetry.StartNewTrace = False NServiceBus.OriginatingEndpoint = HeaderWriterDataBusConvention NServiceBus.OriginatingMachine = MACHINENAME NServiceBus.ReplyToAddress = HeaderWriterDataBusConvention -NServiceBus.TimeSent = 2025-08-19 23:31:19:821593 Z -NServiceBus.Version = 10.0.0 +NServiceBus.TimeSent = 2026-04-29 22:03:16:660116 Z +NServiceBus.Version = 10.2.0 endcode \ No newline at end of file diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDataBusConventionBody.txt b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDataBusConventionBody.txt index ba9954e9a68..bb439843268 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDataBusConventionBody.txt +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDataBusConventionBody.txt @@ -1,4 +1,4 @@ Snippet is code generated by HeaderWriterDataBusConvention.cs startcode HeaderWriterDataBusConventionBody -{"LargeProperty1":"AAAAAAAAAAAAAA==","LargeProperty2":"AAAAAAAAAAAAAA=="} +{"LargeProperty1":null,"LargeProperty2":null} endcode \ No newline at end of file diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDataBusProperty.cs b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDataBusProperty.cs index a6b65465999..7266e47acd5 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDataBusProperty.cs +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDataBusProperty.cs @@ -1,4 +1,7 @@ -namespace Core.Headers.Writers; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +namespace Core.Headers.Writers; using System.Text; using System.Threading; @@ -33,16 +36,20 @@ public async Task Write() endpointConfiguration.RegisterMessageMutator(new Mutator()); endpointConfiguration.UseSerialization(); - var endpointInstance = await Endpoint.Start(endpointConfiguration); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + await host.StartAsync(); + var messageSession = host.Services.GetRequiredService(); var messageToSend = new MessageToSend { LargeProperty1 = new ClaimCheckProperty(new byte[10]), LargeProperty2 = new ClaimCheckProperty(new byte[10]) }; - await endpointInstance.SendLocal(messageToSend); + await messageSession.SendLocal(messageToSend); ManualResetEvent.WaitOne(); - await endpointInstance.Stop(); + await host.StopAsync(); } class MessageToSend : diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDataBusProperty.txt b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDataBusProperty.txt index ddd21a3af63..908146918b0 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDataBusProperty.txt +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDataBusProperty.txt @@ -1,16 +1,20 @@ Snippet is code generated by HeaderWriterDataBusProperty.cs startcode HeaderWriterDataBusProperty -$.diagnostics.originating.hostid = 7f787fc8e0611a3fab8a93c8767f6639 +$.diagnostics.originating.hostid = daaf5ebc8d6a51b7b0dccdd8b15c3626 NServiceBus.ContentType = application/json -NServiceBus.ConversationId = d33bfe42-fd25-40ee-a6b3-b33e0183a242 -NServiceBus.CorrelationId = cb48a338-d6ef-496c-b834-b33e0183a241 +NServiceBus.ConversationId = 83247265-0cba-45c9-b987-b43b016d6444 +NServiceBus.CorrelationId = df2e508a-671e-4439-8bc4-b43b016d6443 +NServiceBus.DataBus.2026-04-29_22/b43dfae2-02b8-4e72-89a2-1281bfaded5b = 2026-04-29_22/b43dfae2-02b8-4e72-89a2-1281bfaded5b +NServiceBus.DataBus.2026-04-29_22/cd7802a5-dba4-43ed-9d8e-b5f6198560e9 = 2026-04-29_22/cd7802a5-dba4-43ed-9d8e-b5f6198560e9 +NServiceBus.DataBusConfig.ContentType = application/json NServiceBus.EnclosedMessageTypes = Core.Headers.Writers.MyNamespace.MessageToSend, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null -NServiceBus.MessageId = cb48a338-d6ef-496c-b834-b33e0183a241 +NServiceBus.MessageId = df2e508a-671e-4439-8bc4-b43b016d6443 NServiceBus.MessageIntent = Send +NServiceBus.OpenTelemetry.StartNewTrace = False NServiceBus.OriginatingEndpoint = HeaderWriterDataBusProperty NServiceBus.OriginatingMachine = MACHINENAME NServiceBus.ReplyToAddress = HeaderWriterDataBusProperty -NServiceBus.TimeSent = 2025-08-19 23:31:19:892927 Z -NServiceBus.Version = 10.0.0 +NServiceBus.TimeSent = 2026-04-29 22:10:21:027928 Z +NServiceBus.Version = 10.2.0 endcode \ No newline at end of file diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDataBusPropertyBody.txt b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDataBusPropertyBody.txt index 278bcad3ac8..92e4a209d7a 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDataBusPropertyBody.txt +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDataBusPropertyBody.txt @@ -1,4 +1,4 @@ Snippet is code generated by HeaderWriterDataBusProperty.cs startcode HeaderWriterDataBusPropertyBody -{"LargeProperty1":{"Key":null,"HasValue":true},"LargeProperty2":{"Key":null,"HasValue":true}} +{"LargeProperty1":{"Key":"2026-04-29_22/b43dfae2-02b8-4e72-89a2-1281bfaded5b","HasValue":true},"LargeProperty2":{"Key":"2026-04-29_22/cd7802a5-dba4-43ed-9d8e-b5f6198560e9","HasValue":true}} endcode \ No newline at end of file diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDefer.cs b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDefer.cs index 4242788136f..841875be329 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDefer.cs +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDefer.cs @@ -1,4 +1,7 @@ -namespace Core.Headers.Writers; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +namespace Core.Headers.Writers; using System; using System.Threading; @@ -34,13 +37,17 @@ public async Task Write() routing.RouteToEndpoint(GetType().Assembly, EndpointName); endpointConfiguration.UseSerialization(); - var endpointInstance = await Endpoint.Start(endpointConfiguration); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + await host.StartAsync(); + var messageSession = host.Services.GetRequiredService(); var options = new SendOptions(); options.DelayDeliveryWith(TimeSpan.FromMilliseconds(10)); - await endpointInstance.Send(new MessageToSend(), options); + await messageSession.Send(new MessageToSend(), options); ManualResetEvent.WaitOne(); - await endpointInstance.Stop(); + await host.StopAsync(); } class MessageToSend : diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDefer.txt b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDefer.txt index aade0262c86..c103a1603db 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDefer.txt +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterDefer.txt @@ -1,17 +1,18 @@ Snippet is code generated by HeaderWriterDefer.cs startcode HeaderWriterDefer -$.diagnostics.originating.hostid = 7f787fc8e0611a3fab8a93c8767f6639 +$.diagnostics.originating.hostid = daaf5ebc8d6a51b7b0dccdd8b15c3626 NServiceBus.ContentType = application/json -NServiceBus.ConversationId = 56628c36-4b51-40b7-82b9-b33e0183a25a -NServiceBus.CorrelationId = a3c08b1a-e6ea-4601-b20a-b33e0183a25a -NServiceBus.DeliverAt = 2025-08-19 23:31:19:983254 Z +NServiceBus.ConversationId = f777b9ea-ee0d-4a22-9489-b43b016db0cc +NServiceBus.CorrelationId = c8c492ed-bb3f-4ecd-9d8c-b43b016db0cc +NServiceBus.DeliverAt = 2026-04-29 22:11:26:340982 Z NServiceBus.EnclosedMessageTypes = Core.Headers.Writers.MyNamespace.MessageToSend, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null -NServiceBus.MessageId = a3c08b1a-e6ea-4601-b20a-b33e0183a25a +NServiceBus.MessageId = c8c492ed-bb3f-4ecd-9d8c-b43b016db0cc NServiceBus.MessageIntent = Send +NServiceBus.OpenTelemetry.StartNewTrace = False NServiceBus.OriginatingEndpoint = HeaderWriterDefer NServiceBus.OriginatingMachine = MACHINENAME NServiceBus.ReplyToAddress = HeaderWriterDefer -NServiceBus.TimeSent = 2025-08-19 23:31:19:973254 Z -NServiceBus.Version = 10.0.0 +NServiceBus.TimeSent = 2026-04-29 22:11:26:330982 Z +NServiceBus.Version = 10.2.0 endcode \ No newline at end of file diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterEncryption.cs b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterEncryption.cs index f4135489245..929a8997550 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterEncryption.cs +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterEncryption.cs @@ -1,4 +1,7 @@ -namespace Core.Headers.Writers; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +namespace Core.Headers.Writers; using System; using System.Text; @@ -46,14 +49,20 @@ public async Task Write() endpointConfiguration.RegisterMessageMutator(new Mutator()); endpointConfiguration.UseSerialization(); - var endpointInstance = await Endpoint.Start(endpointConfiguration); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + await host.StartAsync(); + var messageSession = host.Services.GetRequiredService(); + var messageToSend = new MessageToSend { EncryptedProperty1 = "String 1", EncryptedProperty2 = "String 2" }; - await endpointInstance.SendLocal(messageToSend); + await messageSession.SendLocal(messageToSend); ManualResetEvent.WaitOne(); + await host.StopAsync(); } class MessageToSend : diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterEncryption.txt b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterEncryption.txt index fdbef8b0160..ac181e5fffb 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterEncryption.txt +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterEncryption.txt @@ -1,16 +1,17 @@ Snippet is code generated by HeaderWriterEncryption.cs startcode HeaderWriterEncryption -$.diagnostics.originating.hostid = 7f787fc8e0611a3fab8a93c8767f6639 +$.diagnostics.originating.hostid = daaf5ebc8d6a51b7b0dccdd8b15c3626 NServiceBus.ContentType = application/json -NServiceBus.ConversationId = ea11a77d-e866-4041-8f44-b33e0183a39d -NServiceBus.CorrelationId = 755aa2ab-7fa9-4023-be06-b33e0183a39d +NServiceBus.ConversationId = 31e0cbc0-fcb9-4a9a-b0ab-b43b016dd62d +NServiceBus.CorrelationId = 1c474ad3-d00e-4477-9e49-b43b016dd62c NServiceBus.EnclosedMessageTypes = Core.Headers.Writers.MyNamespace.MessageToSend, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null -NServiceBus.MessageId = 755aa2ab-7fa9-4023-be06-b33e0183a39d +NServiceBus.MessageId = 1c474ad3-d00e-4477-9e49-b43b016dd62c NServiceBus.MessageIntent = Send +NServiceBus.OpenTelemetry.StartNewTrace = False NServiceBus.OriginatingEndpoint = HeaderWriterEncryption NServiceBus.OriginatingMachine = MACHINENAME NServiceBus.ReplyToAddress = HeaderWriterEncryption -NServiceBus.TimeSent = 2025-08-19 23:31:21:051355 Z -NServiceBus.Version = 10.0.0 +NServiceBus.TimeSent = 2026-04-29 22:11:58:229357 Z +NServiceBus.Version = 10.2.0 endcode \ No newline at end of file diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterError.cs b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterError.cs index e95ca9b798d..3cbe2de9a72 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterError.cs +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterError.cs @@ -1,4 +1,7 @@ -namespace Core.Headers.Writers; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +namespace Core.Headers.Writers; using System; using System.Threading; @@ -30,7 +33,10 @@ public async Task Write() errorIngestion.Pipeline.Register(typeof(ErrorMutator), "Capture headers on failed messages"); errorIngestion.UseSerialization(); - await Endpoint.Start(errorIngestion); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(errorIngestion); + var host = builder.Build(); + await host.StartAsync(); var endpointConfiguration = new EndpointConfiguration(endpointName); endpointConfiguration.SendFailedMessagesTo("error"); @@ -48,10 +54,17 @@ public async Task Write() settings.NumberOfRetries(0); }); - var endpointInstance = await Endpoint.Start(endpointConfiguration); + var builder2 = Host.CreateApplicationBuilder(); + builder2.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host2 = builder2.Build(); + await host2.StartAsync(); + var messageSession = host2.Services.GetRequiredService(); - await endpointInstance.SendLocal(new MessageToSend()); + await messageSession.SendLocal(new MessageToSend()); ManualResetEvent.WaitOne(); + + await host.StopAsync(); + await host2.StopAsync(); } class MessageToSend : diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterErrorError.txt b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterErrorError.txt index 8be48b87b2d..acc68dd539f 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterErrorError.txt +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterErrorError.txt @@ -1,46 +1,47 @@ Snippet is code generated by HeaderWriterError.cs startcode HeaderWriterErrorError $.diagnostics.hostdisplayname = MACHINENAME -$.diagnostics.hostid = 7f787fc8e0611a3fab8a93c8767f6639 -$.diagnostics.originating.hostid = 7f787fc8e0611a3fab8a93c8767f6639 +$.diagnostics.hostid = daaf5ebc8d6a51b7b0dccdd8b15c3626 +$.diagnostics.originating.hostid = daaf5ebc8d6a51b7b0dccdd8b15c3626 NServiceBus.ContentType = application/json -NServiceBus.ConversationId = bcb83e59-4b09-4a58-aba5-b33e0183a3a6 -NServiceBus.CorrelationId = 8b1c61fd-903c-49ff-9b0b-b33e0183a3a6 +NServiceBus.ConversationId = be6afcc4-3295-4b6c-8d2f-b43b016c458b +NServiceBus.CorrelationId = eb8cf6f5-6817-4e9f-ba8e-b43b016c458a NServiceBus.EnclosedMessageTypes = Core.Headers.Writers.MyNamespace.MessageToSend, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null NServiceBus.ExceptionInfo.Data.Handler canceled = False -NServiceBus.ExceptionInfo.Data.Handler failure time = 2025-08-19 23:31:21:114729 Z -NServiceBus.ExceptionInfo.Data.Handler start time = 2025-08-19 23:31:21:114684 Z +NServiceBus.ExceptionInfo.Data.Handler failure time = 2026-04-29 22:06:16:405692 Z +NServiceBus.ExceptionInfo.Data.Handler start time = 2026-04-29 22:06:16:405647 Z NServiceBus.ExceptionInfo.Data.Handler type = Core.Headers.Writers.MyNamespace.MessageHandler -NServiceBus.ExceptionInfo.Data.Message ID = 8b1c61fd-903c-49ff-9b0b-b33e0183a3a6 +NServiceBus.ExceptionInfo.Data.Message ID = eb8cf6f5-6817-4e9f-ba8e-b43b016c458a NServiceBus.ExceptionInfo.Data.Message type = Core.Headers.Writers.MyNamespace.MessageToSend NServiceBus.ExceptionInfo.Data.Pipeline canceled = False -NServiceBus.ExceptionInfo.Data.Transport message ID = 999dd2b0-073a-4c8d-ad72-f61dfdb6e912 +NServiceBus.ExceptionInfo.Data.Transport message ID = 737be1a4-a70c-4e9f-a5e7-c4d948f75a60 NServiceBus.ExceptionInfo.ExceptionType = System.Exception -NServiceBus.ExceptionInfo.HelpLink = NServiceBus.ExceptionInfo.Message = The exception message from the handler. NServiceBus.ExceptionInfo.Source = Core_10 NServiceBus.ExceptionInfo.StackTrace = System.Exception: The exception message from the handler. at Core.Headers.Writers.HeaderWriterError.MessageHandler.Handle(MessageToSend message, IMessageHandlerContext context) - at NServiceBus.Pipeline.MessageHandler.Invoke(Object message, IMessageHandlerContext handlerContext) at NServiceBus.InvokeHandlerTerminator.Terminate(IInvokeHandlerContext context) at NServiceBus.LoadHandlersConnector.Invoke(IIncomingLogicalMessageContext context, Func2 stage) at NServiceBus.LoadHandlersConnector.Invoke(IIncomingLogicalMessageContext context, Func2 stage) at NServiceBus.DeserializeMessageConnector.Invoke(IIncomingPhysicalMessageContext context, Func2 stage) at NServiceBus.ProcessingStatisticsBehavior.Invoke(IIncomingPhysicalMessageContext context, Func2 next) at NServiceBus.TransportReceiveToPhysicalMessageConnector.Invoke(ITransportReceiveContext context, Func2 next) + at NServiceBus.TransportReceiveToPhysicalMessageConnector.Invoke(ITransportReceiveContext context, Func2 next) at NServiceBus.RetryAcknowledgementBehavior.Invoke(ITransportReceiveContext context, Func2 next) at NServiceBus.MainPipelineExecutor.Invoke(MessageContext messageContext, CancellationToken cancellationToken) at NServiceBus.MainPipelineExecutor.Invoke(MessageContext messageContext, CancellationToken cancellationToken) + at NServiceBus.LogWrappedMessageReceiver.<>c__DisplayClass12_0.<g__ScopedOnMessage|0>d.MoveNext() at NServiceBus.LearningTransportMessagePump.ProcessFile(ILearningTransportTransaction transaction, String messageId, CancellationToken messageProcessingCancellationToken) NServiceBus.FailedQ = HeaderWriterError -NServiceBus.MessageId = 8b1c61fd-903c-49ff-9b0b-b33e0183a3a6 +NServiceBus.MessageId = eb8cf6f5-6817-4e9f-ba8e-b43b016c458a NServiceBus.MessageIntent = Send +NServiceBus.OpenTelemetry.StartNewTrace = False NServiceBus.OriginatingEndpoint = HeaderWriterError NServiceBus.OriginatingMachine = MACHINENAME NServiceBus.ProcessingEndpoint = HeaderWriterError NServiceBus.ProcessingMachine = MACHINENAME NServiceBus.ReplyToAddress = HeaderWriterError -NServiceBus.TimeOfFailure = 2025-08-19 23:31:21:115187 Z -NServiceBus.TimeSent = 2025-08-19 23:31:21:079952 Z -NServiceBus.Version = 10.0.0 +NServiceBus.TimeOfFailure = 2026-04-29 22:06:16:406166 Z +NServiceBus.TimeSent = 2026-04-29 22:06:16:354264 Z +NServiceBus.Version = 10.2.0 endcode \ No newline at end of file diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterErrorSending.txt b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterErrorSending.txt index b24bc9c9334..85f8c833569 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterErrorSending.txt +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterErrorSending.txt @@ -1,16 +1,17 @@ Snippet is code generated by HeaderWriterError.cs startcode HeaderWriterErrorSending -$.diagnostics.originating.hostid = 7f787fc8e0611a3fab8a93c8767f6639 +$.diagnostics.originating.hostid = daaf5ebc8d6a51b7b0dccdd8b15c3626 NServiceBus.ContentType = application/json -NServiceBus.ConversationId = bcb83e59-4b09-4a58-aba5-b33e0183a3a6 -NServiceBus.CorrelationId = 8b1c61fd-903c-49ff-9b0b-b33e0183a3a6 +NServiceBus.ConversationId = be6afcc4-3295-4b6c-8d2f-b43b016c458b +NServiceBus.CorrelationId = eb8cf6f5-6817-4e9f-ba8e-b43b016c458a NServiceBus.EnclosedMessageTypes = Core.Headers.Writers.MyNamespace.MessageToSend, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null -NServiceBus.MessageId = 8b1c61fd-903c-49ff-9b0b-b33e0183a3a6 +NServiceBus.MessageId = eb8cf6f5-6817-4e9f-ba8e-b43b016c458a NServiceBus.MessageIntent = Send +NServiceBus.OpenTelemetry.StartNewTrace = False NServiceBus.OriginatingEndpoint = HeaderWriterError NServiceBus.OriginatingMachine = MACHINENAME NServiceBus.ReplyToAddress = HeaderWriterError -NServiceBus.TimeSent = 2025-08-19 23:31:21:079952 Z -NServiceBus.Version = 10.0.0 +NServiceBus.TimeSent = 2026-04-29 22:06:16:354264 Z +NServiceBus.Version = 10.2.0 endcode \ No newline at end of file diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterPublish.cs b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterPublish.cs index c943cb910fb..b3600e057df 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterPublish.cs +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterPublish.cs @@ -1,4 +1,7 @@ -namespace Core.Headers.Writers; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +namespace Core.Headers.Writers; using System.Threading; using System.Threading.Tasks; @@ -32,13 +35,17 @@ public async Task Write() endpointConfiguration.UseTransport(new LearningTransport {StorageDirectory = TestContext.CurrentContext.TestDirectory}); endpointConfiguration.UseSerialization(); - var endpointInstance = await Endpoint.Start(endpointConfiguration); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + await host.StartAsync(); + var messageSession = host.Services.GetRequiredService(); // give time for the subscription to happen await Task.Delay(3000); - await endpointInstance.Publish(new MessageToPublish()); + await messageSession.Publish(new MessageToPublish()); ManualResetEvent.WaitOne(); - await endpointInstance.Stop(); + await host.StopAsync(); } class MessageToPublish : diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterPublish.txt b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterPublish.txt index 73f6e729af3..c987ddd1643 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterPublish.txt +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterPublish.txt @@ -1,16 +1,17 @@ Snippet is code generated by HeaderWriterPublish.cs startcode HeaderWriterPublish -$.diagnostics.originating.hostid = 7f787fc8e0611a3fab8a93c8767f6639 +$.diagnostics.originating.hostid = daaf5ebc8d6a51b7b0dccdd8b15c3626 NServiceBus.ContentType = application/json -NServiceBus.ConversationId = df681185-4bad-440a-af2a-b33e0183a73d -NServiceBus.CorrelationId = 63df65f7-4718-4813-af5d-b33e0183a73b +NServiceBus.ConversationId = 35b4c487-97b1-47cb-9181-b43b016d4482 +NServiceBus.CorrelationId = da253bc4-68bd-42f3-ac7f-b43b016d4482 NServiceBus.EnclosedMessageTypes = Core.Headers.Writers.MyNamespace.MessageToPublish, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null -NServiceBus.MessageId = 63df65f7-4718-4813-af5d-b33e0183a73b +NServiceBus.MessageId = da253bc4-68bd-42f3-ac7f-b43b016d4482 NServiceBus.MessageIntent = Publish +NServiceBus.OpenTelemetry.StartNewTrace = True NServiceBus.OriginatingEndpoint = HeaderWriterPublish NServiceBus.OriginatingMachine = MACHINENAME NServiceBus.ReplyToAddress = HeaderWriterPublish -NServiceBus.TimeSent = 2025-08-19 23:31:24:148005 Z -NServiceBus.Version = 10.0.0 +NServiceBus.TimeSent = 2026-04-29 22:09:53:925402 Z +NServiceBus.Version = 10.2.0 endcode \ No newline at end of file diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterReply.cs b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterReply.cs index ba1dfad5caa..c737779399a 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterReply.cs +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterReply.cs @@ -1,4 +1,7 @@ -namespace Core.Headers.Writers; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +namespace Core.Headers.Writers; using System.Threading; using System.Threading.Tasks; @@ -31,9 +34,15 @@ public async Task Write() endpointConfiguration.RegisterMessageMutator(new Mutator()); endpointConfiguration.UseSerialization(); - var endpointInstance = await Endpoint.Start(endpointConfiguration); - await endpointInstance.SendLocal(new MessageToSend()); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + await host.StartAsync(); + var messageSession = host.Services.GetRequiredService(); + + await messageSession.SendLocal(new MessageToSend()); ManualResetEvent.WaitOne(); + await host.StopAsync(); } class MessageToSend : diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterReplyReplying.txt b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterReplyReplying.txt index c5ab6e7b0a8..555b2fdcecb 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterReplyReplying.txt +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterReplyReplying.txt @@ -1,17 +1,17 @@ Snippet is code generated by HeaderWriterReply.cs startcode HeaderWriterReplyReplying -$.diagnostics.originating.hostid = 7f787fc8e0611a3fab8a93c8767f6639 +$.diagnostics.originating.hostid = daaf5ebc8d6a51b7b0dccdd8b15c3626 NServiceBus.ContentType = application/json -NServiceBus.ConversationId = 4496a557-fc43-476b-86a8-b33e0183a757 -NServiceBus.CorrelationId = 2f2a3612-76eb-46b8-ace9-b33e0183a757 +NServiceBus.ConversationId = 3a0fb0c4-8b60-4cad-a6db-b43b016d03ef +NServiceBus.CorrelationId = 0a96c254-e745-4296-b1a5-b43b016d03ee NServiceBus.EnclosedMessageTypes = Core.Headers.Writers.MyNamespace.MessageToReply, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null -NServiceBus.MessageId = c6cf2813-7f53-4b71-aff9-b33e0183a75b +NServiceBus.MessageId = 32ac55a7-5a66-4ca4-94ec-b43b016d03f9 NServiceBus.MessageIntent = Reply NServiceBus.OriginatingEndpoint = HeaderWriterReply NServiceBus.OriginatingMachine = MACHINENAME -NServiceBus.RelatedTo = 2f2a3612-76eb-46b8-ace9-b33e0183a757 +NServiceBus.RelatedTo = 0a96c254-e745-4296-b1a5-b43b016d03ee NServiceBus.ReplyToAddress = HeaderWriterReply -NServiceBus.TimeSent = 2025-08-19 23:31:24:245407 Z -NServiceBus.Version = 10.0.0 +NServiceBus.TimeSent = 2026-04-29 22:08:58:850190 Z +NServiceBus.Version = 10.2.0 endcode \ No newline at end of file diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterReplySending.txt b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterReplySending.txt index f51c4abce5a..6ae5eafdc42 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterReplySending.txt +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterReplySending.txt @@ -1,16 +1,17 @@ Snippet is code generated by HeaderWriterReply.cs startcode HeaderWriterReplySending -$.diagnostics.originating.hostid = 7f787fc8e0611a3fab8a93c8767f6639 +$.diagnostics.originating.hostid = daaf5ebc8d6a51b7b0dccdd8b15c3626 NServiceBus.ContentType = application/json -NServiceBus.ConversationId = 4496a557-fc43-476b-86a8-b33e0183a757 -NServiceBus.CorrelationId = 2f2a3612-76eb-46b8-ace9-b33e0183a757 +NServiceBus.ConversationId = 3a0fb0c4-8b60-4cad-a6db-b43b016d03ef +NServiceBus.CorrelationId = 0a96c254-e745-4296-b1a5-b43b016d03ee NServiceBus.EnclosedMessageTypes = Core.Headers.Writers.MyNamespace.MessageToSend, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null -NServiceBus.MessageId = 2f2a3612-76eb-46b8-ace9-b33e0183a757 +NServiceBus.MessageId = 0a96c254-e745-4296-b1a5-b43b016d03ee NServiceBus.MessageIntent = Send +NServiceBus.OpenTelemetry.StartNewTrace = False NServiceBus.OriginatingEndpoint = HeaderWriterReply NServiceBus.OriginatingMachine = MACHINENAME NServiceBus.ReplyToAddress = HeaderWriterReply -NServiceBus.TimeSent = 2025-08-19 23:31:24:231783 Z -NServiceBus.Version = 10.0.0 +NServiceBus.TimeSent = 2026-04-29 22:08:58:819617 Z +NServiceBus.Version = 10.2.0 endcode \ No newline at end of file diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterReturn.cs b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterReturn.cs index e6ecef52054..c703744c7ae 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterReturn.cs +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterReturn.cs @@ -1,4 +1,7 @@ -namespace Core.Headers.Writers; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +namespace Core.Headers.Writers; using System.Threading; using System.Threading.Tasks; @@ -32,9 +35,15 @@ public async Task Write() endpointConfiguration.RegisterMessageMutator(new Mutator()); endpointConfiguration.UseSerialization(); - var endpointInstance = await Endpoint.Start(endpointConfiguration); - await endpointInstance.SendLocal(new MessageToSend()); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + await host.StartAsync(); + var messageSession = host.Services.GetRequiredService(); + await messageSession.SendLocal(new MessageToSend()); + ManualResetEvent.WaitOne(); + await host.StopAsync(); } class MessageToSend : diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterReturnReturning.txt b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterReturnReturning.txt index 117f89b5610..f28479a9762 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterReturnReturning.txt +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterReturnReturning.txt @@ -1,17 +1,17 @@ Snippet is code generated by HeaderWriterReturn.cs startcode HeaderWriterReturnReturning -$.diagnostics.originating.hostid = 7f787fc8e0611a3fab8a93c8767f6639 +$.diagnostics.originating.hostid = daaf5ebc8d6a51b7b0dccdd8b15c3626 NServiceBus.ControlMessage = True -NServiceBus.ConversationId = 0f975aa7-6f69-4202-85a7-b33e0183a764 -NServiceBus.CorrelationId = 9a31ba7d-1ec8-4cdc-acf8-b33e0183a764 -NServiceBus.MessageId = 69fddbd6-046e-4d17-866c-b33e0183a768 +NServiceBus.ConversationId = 418b54ae-859f-48e2-ae5c-b43b016ca105 +NServiceBus.CorrelationId = dd8dda40-2158-4111-9041-b43b016ca104 +NServiceBus.MessageId = 7a8293e2-6440-4072-8dc0-b43b016ca10f NServiceBus.MessageIntent = Reply NServiceBus.OriginatingEndpoint = HeaderWriterReturn NServiceBus.OriginatingMachine = MACHINENAME -NServiceBus.RelatedTo = 9a31ba7d-1ec8-4cdc-acf8-b33e0183a764 +NServiceBus.RelatedTo = dd8dda40-2158-4111-9041-b43b016ca104 NServiceBus.ReplyToAddress = HeaderWriterReturn NServiceBus.ReturnMessage.ErrorCode = 100 -NServiceBus.TimeSent = 2025-08-19 23:31:24:287864 Z -NServiceBus.Version = 10.0.0 +NServiceBus.TimeSent = 2026-04-29 22:07:34:444507 Z +NServiceBus.Version = 10.2.0 endcode \ No newline at end of file diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterReturnSending.txt b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterReturnSending.txt index f928fd09998..3b81f8c7248 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterReturnSending.txt +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterReturnSending.txt @@ -1,16 +1,17 @@ Snippet is code generated by HeaderWriterReturn.cs startcode HeaderWriterReturnSending -$.diagnostics.originating.hostid = 7f787fc8e0611a3fab8a93c8767f6639 +$.diagnostics.originating.hostid = daaf5ebc8d6a51b7b0dccdd8b15c3626 NServiceBus.ContentType = application/json -NServiceBus.ConversationId = 0f975aa7-6f69-4202-85a7-b33e0183a764 -NServiceBus.CorrelationId = 9a31ba7d-1ec8-4cdc-acf8-b33e0183a764 +NServiceBus.ConversationId = 418b54ae-859f-48e2-ae5c-b43b016ca105 +NServiceBus.CorrelationId = dd8dda40-2158-4111-9041-b43b016ca104 NServiceBus.EnclosedMessageTypes = Core.Headers.Writers.MyNamespace.MessageToSend, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null -NServiceBus.MessageId = 9a31ba7d-1ec8-4cdc-acf8-b33e0183a764 +NServiceBus.MessageId = dd8dda40-2158-4111-9041-b43b016ca104 NServiceBus.MessageIntent = Send +NServiceBus.OpenTelemetry.StartNewTrace = False NServiceBus.OriginatingEndpoint = HeaderWriterReturn NServiceBus.OriginatingMachine = MACHINENAME NServiceBus.ReplyToAddress = HeaderWriterReturn -NServiceBus.TimeSent = 2025-08-19 23:31:24:274905 Z -NServiceBus.Version = 10.0.0 +NServiceBus.TimeSent = 2026-04-29 22:07:34:413876 Z +NServiceBus.Version = 10.2.0 endcode \ No newline at end of file diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterSaga.cs b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterSaga.cs index 7dbacda16c2..fb76d88178f 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterSaga.cs +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterSaga.cs @@ -1,4 +1,7 @@ -namespace Core.Headers.Writers; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +namespace Core.Headers.Writers; using System; using System.Threading; @@ -31,9 +34,15 @@ public async Task Write() endpointConfiguration.RegisterMessageMutator(new Mutator()); endpointConfiguration.UseSerialization(); - var endpointInstance = await Endpoint.Start(endpointConfiguration); - await endpointInstance.SendLocal(new StartSaga1Message { Guid = Guid.NewGuid() }); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + await host.StartAsync(); + var messageSession = host.Services.GetRequiredService(); + + await messageSession.SendLocal(new StartSaga1Message { Guid = Guid.NewGuid() }); CountdownEvent.Wait(); + await host.StopAsync(); } class StartSaga1Message : diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterSagaReplying.txt b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterSagaReplying.txt index a100bbf25b9..82eb3bc8e4a 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterSagaReplying.txt +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterSagaReplying.txt @@ -1,21 +1,21 @@ Snippet is code generated by HeaderWriterSaga.cs startcode HeaderWriterSagaReplying -$.diagnostics.originating.hostid = 7f787fc8e0611a3fab8a93c8767f6639 +$.diagnostics.originating.hostid = daaf5ebc8d6a51b7b0dccdd8b15c3626 NServiceBus.ContentType = application/json -NServiceBus.ConversationId = 828cb54c-cc27-4e00-b0cb-b33e0183a771 -NServiceBus.CorrelationId = dda21c82-6aa4-4ce9-83cd-b33e0183a770 +NServiceBus.ConversationId = 4119c812-d313-46c0-8b02-b43b016ccb4a +NServiceBus.CorrelationId = 60ae1074-a3ac-4047-be45-b43b016ccb49 NServiceBus.EnclosedMessageTypes = Core.Headers.Writers.MyNamespace.ReplyFromSagaMessage, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null -NServiceBus.MessageId = 15f89e94-686b-48b4-a8b6-b33e0183a77b +NServiceBus.MessageId = 682e3fce-d786-4a22-9d1d-b43b016ccb5b NServiceBus.MessageIntent = Reply NServiceBus.OriginatingEndpoint = HeaderWriterSaga NServiceBus.OriginatingMachine = MACHINENAME -NServiceBus.OriginatingSagaId = 1b5084e2-a450-fcdc-0256-15fe43cc7cc4 +NServiceBus.OriginatingSagaId = b8b235ac-2601-0e5f-0216-3d2b330d90b0 NServiceBus.OriginatingSagaType = Core.Headers.Writers.MyNamespace.Saga2, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null -NServiceBus.RelatedTo = e279c016-7f50-45ed-bcca-b33e0183a776 +NServiceBus.RelatedTo = 4cb483eb-a01a-41f3-92df-b43b016ccb55 NServiceBus.ReplyToAddress = HeaderWriterSaga -NServiceBus.SagaId = ebfa2ab2-0847-35bf-021f-780fe7fc0ec9 +NServiceBus.SagaId = 14cfe524-7377-1367-6615-9061c2a79edd NServiceBus.SagaType = Core.Headers.Writers.MyNamespace.Saga1, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null -NServiceBus.TimeSent = 2025-08-19 23:31:24:350393 Z -NServiceBus.Version = 10.0.0 +NServiceBus.TimeSent = 2026-04-29 22:08:10:537452 Z +NServiceBus.Version = 10.2.0 endcode \ No newline at end of file diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterSagaReplyingToOriginator.txt b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterSagaReplyingToOriginator.txt index 1d186969b79..17df40d1188 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterSagaReplyingToOriginator.txt +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterSagaReplyingToOriginator.txt @@ -1,19 +1,19 @@ Snippet is code generated by HeaderWriterSaga.cs startcode HeaderWriterSagaReplyingToOriginator -$.diagnostics.originating.hostid = 7f787fc8e0611a3fab8a93c8767f6639 +$.diagnostics.originating.hostid = daaf5ebc8d6a51b7b0dccdd8b15c3626 NServiceBus.ContentType = application/json -NServiceBus.ConversationId = 828cb54c-cc27-4e00-b0cb-b33e0183a771 -NServiceBus.CorrelationId = e279c016-7f50-45ed-bcca-b33e0183a776 +NServiceBus.ConversationId = 4119c812-d313-46c0-8b02-b43b016ccb4a +NServiceBus.CorrelationId = 4cb483eb-a01a-41f3-92df-b43b016ccb55 NServiceBus.EnclosedMessageTypes = Core.Headers.Writers.MyNamespace.ReplyToOriginatorFromSagaMessage, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null -NServiceBus.MessageId = 8fb5b88c-c839-40e4-a4a9-b33e0183a77b +NServiceBus.MessageId = 161f3ddb-e7b6-407f-835f-b43b016ccb5b NServiceBus.MessageIntent = Reply NServiceBus.OriginatingEndpoint = HeaderWriterSaga NServiceBus.OriginatingMachine = MACHINENAME -NServiceBus.OriginatingSagaId = 1b5084e2-a450-fcdc-0256-15fe43cc7cc4 +NServiceBus.OriginatingSagaId = b8b235ac-2601-0e5f-0216-3d2b330d90b0 NServiceBus.OriginatingSagaType = Core.Headers.Writers.MyNamespace.Saga2, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null -NServiceBus.RelatedTo = e279c016-7f50-45ed-bcca-b33e0183a776 +NServiceBus.RelatedTo = 4cb483eb-a01a-41f3-92df-b43b016ccb55 NServiceBus.ReplyToAddress = HeaderWriterSaga -NServiceBus.TimeSent = 2025-08-19 23:31:24:350897 Z -NServiceBus.Version = 10.0.0 +NServiceBus.TimeSent = 2026-04-29 22:08:10:537889 Z +NServiceBus.Version = 10.2.0 endcode \ No newline at end of file diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterSagaSending.txt b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterSagaSending.txt index 5e0e4827a66..be49dd026cc 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterSagaSending.txt +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterSagaSending.txt @@ -1,19 +1,20 @@ Snippet is code generated by HeaderWriterSaga.cs startcode HeaderWriterSagaSending -$.diagnostics.originating.hostid = 7f787fc8e0611a3fab8a93c8767f6639 +$.diagnostics.originating.hostid = daaf5ebc8d6a51b7b0dccdd8b15c3626 NServiceBus.ContentType = application/json -NServiceBus.ConversationId = 828cb54c-cc27-4e00-b0cb-b33e0183a771 -NServiceBus.CorrelationId = dda21c82-6aa4-4ce9-83cd-b33e0183a770 +NServiceBus.ConversationId = 4119c812-d313-46c0-8b02-b43b016ccb4a +NServiceBus.CorrelationId = 60ae1074-a3ac-4047-be45-b43b016ccb49 NServiceBus.EnclosedMessageTypes = Core.Headers.Writers.MyNamespace.SendFromSagaMessage, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null -NServiceBus.MessageId = e279c016-7f50-45ed-bcca-b33e0183a776 +NServiceBus.MessageId = 4cb483eb-a01a-41f3-92df-b43b016ccb55 NServiceBus.MessageIntent = Send +NServiceBus.OpenTelemetry.StartNewTrace = False NServiceBus.OriginatingEndpoint = HeaderWriterSaga NServiceBus.OriginatingMachine = MACHINENAME -NServiceBus.OriginatingSagaId = ebfa2ab2-0847-35bf-021f-780fe7fc0ec9 +NServiceBus.OriginatingSagaId = 14cfe524-7377-1367-6615-9061c2a79edd NServiceBus.OriginatingSagaType = Core.Headers.Writers.MyNamespace.Saga1, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null -NServiceBus.RelatedTo = dda21c82-6aa4-4ce9-83cd-b33e0183a770 +NServiceBus.RelatedTo = 60ae1074-a3ac-4047-be45-b43b016ccb49 NServiceBus.ReplyToAddress = HeaderWriterSaga -NServiceBus.TimeSent = 2025-08-19 23:31:24:333237 Z -NServiceBus.Version = 10.0.0 +NServiceBus.TimeSent = 2026-04-29 22:08:10:516632 Z +NServiceBus.Version = 10.2.0 endcode \ No newline at end of file diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterSend.cs b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterSend.cs index 2d7305dc7b5..894cb2ad523 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterSend.cs +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterSend.cs @@ -1,4 +1,7 @@ -namespace Core.Headers.Writers; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +namespace Core.Headers.Writers; using System.Threading; using System.Threading.Tasks; @@ -30,9 +33,16 @@ public async Task Write() endpointConfiguration.RegisterMessageMutator(new Mutator()); endpointConfiguration.UseSerialization(); - var endpointInstance = await Endpoint.Start(endpointConfiguration); - await endpointInstance.SendLocal(new MessageToSend()); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + await host.StartAsync(); + + var messageSession = host.Services.GetRequiredService(); + + await messageSession.SendLocal(new MessageToSend()); ManualResetEvent.WaitOne(); + await host.StopAsync(); } class MessageToSend : diff --git a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterSend.txt b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterSend.txt index 21943cd896e..eb6c366f9a4 100644 --- a/Snippets/Core/Core_10/Headers/Writers/HeaderWriterSend.txt +++ b/Snippets/Core/Core_10/Headers/Writers/HeaderWriterSend.txt @@ -1,16 +1,17 @@ Snippet is code generated by HeaderWriterSend.cs startcode HeaderWriterSend -$.diagnostics.originating.hostid = 7f787fc8e0611a3fab8a93c8767f6639 +$.diagnostics.originating.hostid = daaf5ebc8d6a51b7b0dccdd8b15c3626 NServiceBus.ContentType = application/json -NServiceBus.ConversationId = ef801307-4f3e-4195-aa73-b33e0183a786 -NServiceBus.CorrelationId = 730b61b0-2d71-4c2b-93ae-b33e0183a786 +NServiceBus.ConversationId = 1d5fc7ad-0f38-4172-a469-b43b0169b466 +NServiceBus.CorrelationId = 43e9c0c6-57a8-4513-b15a-b43b0169b465 NServiceBus.EnclosedMessageTypes = Core.Headers.Writers.MyNamespace.MessageToSend, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null -NServiceBus.MessageId = 730b61b0-2d71-4c2b-93ae-b33e0183a786 +NServiceBus.MessageId = 43e9c0c6-57a8-4513-b15a-b43b0169b465 NServiceBus.MessageIntent = Send +NServiceBus.OpenTelemetry.StartNewTrace = False NServiceBus.OriginatingEndpoint = HeaderWriterSend NServiceBus.OriginatingMachine = MACHINENAME NServiceBus.ReplyToAddress = HeaderWriterSend -NServiceBus.TimeSent = 2025-08-19 23:31:24:388623 Z -NServiceBus.Version = 10.0.0 +NServiceBus.TimeSent = 2026-04-29 21:56:55:590807 Z +NServiceBus.Version = 10.2.0 endcode \ No newline at end of file diff --git a/Snippets/Core/Core_10/Hosting/Hosting.cs b/Snippets/Core/Core_10/Hosting/Hosting.cs index 9a63d1afff7..32063152f9a 100644 --- a/Snippets/Core/Core_10/Hosting/Hosting.cs +++ b/Snippets/Core/Core_10/Hosting/Hosting.cs @@ -6,18 +6,17 @@ class Hosting { - async Task SendOnly() + void SendOnly() { #region Hosting-SendOnly var endpointConfiguration = new EndpointConfiguration("EndpointName"); endpointConfiguration.SendOnly(); - // Apply other necessary endpoint configuration, e.g. transport - var endpointInstance = await Endpoint.Start(endpointConfiguration); #endregion } +#pragma warning disable CS0618 // Type or member is obsolete async Task Startup() { #region Hosting-Startup @@ -33,6 +32,7 @@ async Task Startup() async Task Shutdown(IEndpointInstance endpointInstance) { + #region Hosting-Shutdown await endpointInstance.Stop(); #endregion @@ -52,4 +52,5 @@ public static void SetInstance(IEndpointInstance endpoint) } } #endregion +#pragma warning restore CS0618 // Type or member is obsolete } \ No newline at end of file diff --git a/Snippets/Core/Core_10/Hosting/StartUpDiagnosticsWriter.cs b/Snippets/Core/Core_10/Hosting/StartUpDiagnosticsWriter.cs index 67020a0f2ec..e0bfdc2f8a3 100644 --- a/Snippets/Core/Core_10/Hosting/StartUpDiagnosticsWriter.cs +++ b/Snippets/Core/Core_10/Hosting/StartUpDiagnosticsWriter.cs @@ -1,4 +1,6 @@ -namespace Core.Hosting; +using Microsoft.Extensions.Hosting; + +namespace Core.Hosting; using System; using System.Linq; @@ -28,11 +30,16 @@ public async Task Write() }); endpointConfiguration.UseSerialization(); - var endpointInstance = await Endpoint.Start(endpointConfiguration); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + await host.StartAsync(); + var jsonFormatted = JToken.Parse(diagnostics).ToString(Formatting.Indented); var abbreviated = jsonFormatted.Split(["\r\n", "\n", "\r"], StringSplitOptions.None).Take(20); var substring = string.Join("\r", abbreviated) + "\r\n..."; SnippetLogger.Write(substring); - await endpointInstance.Stop(); + + await host.StopAsync(); } } \ No newline at end of file diff --git a/Snippets/Core/Core_10/Hosting/StartUpDiagnosticsWriter.txt b/Snippets/Core/Core_10/Hosting/StartUpDiagnosticsWriter.txt index 70cb500e5f7..30b90556c9b 100644 --- a/Snippets/Core/Core_10/Hosting/StartUpDiagnosticsWriter.txt +++ b/Snippets/Core/Core_10/Hosting/StartUpDiagnosticsWriter.txt @@ -1,5 +1,5 @@ Snippet is code generated by StartUpDiagnosticsWriter.cs startcode StartUpDiagnosticsWriter -{ "Container": { "Type": "internal" }, "Endpoint": { "Name": "StartUpDiagnosticsWriter", "SendOnly": false, "NServiceBusVersion": "10.0.0" }, "Features": [ { "Name": "NServiceBus.OpenTelemetryFeature", "EnabledByDefault": false, "Active": false, "PrerequisiteStatus": { "IsSatisfied": true, "Reasons": [] }, "Dependencies": [], "Version": "10.0.0", +{ "Container": { "Type": "external" }, "Endpoint": { "Name": "StartUpDiagnosticsWriter", "SendOnly": false, "NServiceBusVersion": "10.2.0" }, "Features": [ { "Name": "NServiceBus.ReceiveStatisticsFeature", "Enabled": false, "Active": true, "PrerequisiteStatus": { "IsSatisfied": true, "Reasons": [] }, "Dependencies": [], "Version": "10.2.0", ... endcode \ No newline at end of file diff --git a/Snippets/Core/Core_10/Installers.cs b/Snippets/Core/Core_10/Installers.cs index 6158ca31c0b..569fc254dfc 100644 --- a/Snippets/Core/Core_10/Installers.cs +++ b/Snippets/Core/Core_10/Installers.cs @@ -1,4 +1,6 @@ -namespace Core; +using Microsoft.Extensions.Hosting; + +namespace Core; using System; using System.Linq; @@ -9,25 +11,22 @@ class ForInstallationOnReplacement { - async Task Simple(EndpointConfiguration endpointConfiguration) + void Simple(EndpointConfiguration endpointConfiguration) { #region Installers endpointConfiguration.EnableInstallers(); - // this will run the installers - await Endpoint.Start(endpointConfiguration); - #endregion } } class SwitchInstallersWithCommandline { - static EndpointConfiguration endpointConfiguration = new EndpointConfiguration("someEndpoint"); - - public static async Task Main_(string[] args) + public static void InstallersRunWhenNecessaryCommandLine() { + var endpointConfiguration = new EndpointConfiguration("someEndpoint"); + #region InstallersRunWhenNecessaryCommandLine var runInstallers = Environment.GetCommandLineArgs().Any(x => string.Equals(x, "/runInstallers", StringComparison.OrdinalIgnoreCase)); @@ -35,9 +34,6 @@ public static async Task Main_(string[] args) if (runInstallers) { endpointConfiguration.EnableInstallers(); - // This will run the installers but not start the instance. - await Endpoint.Create(endpointConfiguration); - Environment.Exit(0); } #endregion @@ -56,6 +52,7 @@ Task Simple(EndpointConfiguration endpointConfiguration) } #endregion + return Task.CompletedTask; } } @@ -65,30 +62,23 @@ public class InstallerSetup public static async Task MainProgram() { #region installer-setup - var endpointConfiguration = new EndpointConfiguration("my-endpoint"); - // configure endpoint - await Installer.Setup(endpointConfiguration); - #endregion - } -} + var hostBuilder = new HostApplicationBuilder(); + var endpointConfiguration = new EndpointConfiguration("someEndpoint"); -public class InstallerSetupExternallyManagedContainer -{ - public static async Task MainProgram() - { - #region installer-setup-externally-managed-container - var endpointConfiguration = new EndpointConfiguration("my-endpoint"); - // configure endpoint + hostBuilder.Services.AddNServiceBusEndpoint(endpointConfiguration); - var serviceCollection = new ServiceCollection(); - // custom registrations + // On run, this will run the installers and then stop the host + hostBuilder.Services.AddNServiceBusInstallers(); - var installer = Installer.CreateInstallerWithExternallyManagedContainer(endpointConfiguration, serviceCollection); + // OR, this will run the installers and allow the host to continue + hostBuilder.Services.AddNServiceBusInstallers(options => + options.ShutdownBehavior = InstallersShutdownBehavior.Continue); - var serviceProvider = serviceCollection.BuildServiceProvider(); + // This will run the installers with the requested ShutdownBehavior + await hostBuilder.Build() + .RunAsync(); - await installer.Setup(serviceProvider); #endregion } } \ No newline at end of file diff --git a/Snippets/Core/Core_10/InstancePerUnitOfWorkRegistration.cs b/Snippets/Core/Core_10/InstancePerUnitOfWorkRegistration.cs index 194b6730274..e1dca1488a6 100644 --- a/Snippets/Core/Core_10/InstancePerUnitOfWorkRegistration.cs +++ b/Snippets/Core/Core_10/InstancePerUnitOfWorkRegistration.cs @@ -7,6 +7,7 @@ class InstancePerUnitOfWorkRegistration { InstancePerUnitOfWorkRegistration(EndpointConfiguration endpointConfiguration) { +#pragma warning disable CS0618 // Type or member is obsolete #region InstancePerUnitOfWorkRegistration endpointConfiguration.RegisterComponents( @@ -16,6 +17,7 @@ class InstancePerUnitOfWorkRegistration }); #endregion +#pragma warning restore CS0618 // Type or member is obsolete } class InstancePerUnitOfWork { } diff --git a/Snippets/Core/Core_10/Logging/BuiltInConfig.cs b/Snippets/Core/Core_10/Logging/BuiltInConfig.cs index 5eac2a4d17a..92fbd3b19b3 100644 --- a/Snippets/Core/Core_10/Logging/BuiltInConfig.cs +++ b/Snippets/Core/Core_10/Logging/BuiltInConfig.cs @@ -4,6 +4,7 @@ class BuiltInConfig { +#pragma warning disable CS0618 // Type or member is obsolete void ChangingLevel() { @@ -25,5 +26,5 @@ void ChangingDirectory() #endregion } - +#pragma warning restore CS0618 // Type or member is obsolete } \ No newline at end of file diff --git a/Snippets/Core/Core_10/Logging/ModernLogging.cs b/Snippets/Core/Core_10/Logging/ModernLogging.cs new file mode 100644 index 00000000000..0d6267a0556 --- /dev/null +++ b/Snippets/Core/Core_10/Logging/ModernLogging.cs @@ -0,0 +1,51 @@ +namespace Core.Logging; + +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using NServiceBus; + +public class MyMessage : IMessage { } + +#region InjectingILoggerInterface + +public class MyHandler(ILogger logger) : IHandleMessages +{ + public Task Handle(MyMessage message, IMessageHandlerContext context) + { + logger.LogInformation("Handling message"); + return Task.CompletedTask; + } +} + +#endregion + +partial class HighPerformanceLogging +{ + #region UsingLoggerMessageSourceGenerator + [LoggerMessage( + EventId = 0, + Level = LogLevel.Information, + Message = "Processing message {MessageId}")] + static partial void LogProcessingMessage(ILogger logger, string messageId); + #endregion +} + +class Startup +{ + #region ConfiguringRollingFileLogger + void ConfigureHost() + { + var builder = Host.CreateApplicationBuilder(); + + builder.Services.Configure(options => + { + options.Directory = @"C:\logs"; + options.LogLevel = LogLevel.Debug; + options.NumberOfArchiveFilesToKeep = 10; + options.MaxFileSizeInBytes = 10L * 1024 * 1024; + }); + } + #endregion +} diff --git a/Snippets/Core/Core_10/PubSub/Publishing/PublishAtStartup.cs b/Snippets/Core/Core_10/PubSub/Publishing/PublishAtStartup.cs index c968798252c..8c9ac58a40e 100644 --- a/Snippets/Core/Core_10/PubSub/Publishing/PublishAtStartup.cs +++ b/Snippets/Core/Core_10/PubSub/Publishing/PublishAtStartup.cs @@ -1,4 +1,7 @@ -namespace Core.PubSub.Publishing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +namespace Core.PubSub.Publishing; using System.Threading.Tasks; using NServiceBus; @@ -9,8 +12,12 @@ public async Task Publish(EndpointConfiguration endpointConfiguration) { #region publishAtStartup // Other config - var endpointInstance = await Endpoint.Start(endpointConfiguration); - await endpointInstance.Publish(new MyEvent()); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + await host.StartAsync(); + var messageSession = host.Services.GetRequiredService(); + await messageSession.Publish(new MyEvent()); #endregion diff --git a/Snippets/Core/Core_10/Routing/BasicOperations.cs b/Snippets/Core/Core_10/Routing/BasicOperations.cs index 2fc49400afa..65fe9a7f324 100644 --- a/Snippets/Core/Core_10/Routing/BasicOperations.cs +++ b/Snippets/Core/Core_10/Routing/BasicOperations.cs @@ -5,11 +5,11 @@ class BasicOperations { - async Task InterfaceSend(IEndpointInstance endpoint) + async Task InterfaceSend(IMessageSession messageSession) { #region InterfaceSend - await endpoint.Send(message => + await messageSession.Send(message => { message.SomeProperty = "Hello world"; }); @@ -67,13 +67,13 @@ async Task PublishEvent(IMessageCreator messageCreator) #endregion } - async Task Subscribe(IEndpointInstance endpoint) + async Task Subscribe(IMessageSession messageSession) { #region ExplicitSubscribe - await endpoint.Subscribe(); + await messageSession.Subscribe(); - await endpoint.Unsubscribe(); + await messageSession.Unsubscribe(); #endregion } diff --git a/Snippets/Core/Core_10/prerelease.txt b/Snippets/Core/Core_10/prerelease.txt new file mode 100644 index 00000000000..e69de29bb2d diff --git a/Snippets/Core/Core_8/Core_8.csproj b/Snippets/Core/Core_8/Core_8.csproj index 8d714cc0281..1132b83ee0f 100644 --- a/Snippets/Core/Core_8/Core_8.csproj +++ b/Snippets/Core/Core_8/Core_8.csproj @@ -25,7 +25,7 @@ - + diff --git a/menu/menu.yaml b/menu/menu.yaml index 4a27a324727..1f8c535f172 100644 --- a/menu/menu.yaml +++ b/menu/menu.yaml @@ -472,15 +472,19 @@ Articles: - Url: nservicebus/handlers-and-sagas Title: About handlers and sagas - - Url: nservicebus/handlers/async-handlers - Title: Asynchronous Handlers + - Url: nservicebus/handlers-and-sagas-registration + Title: Registration - Url: nservicebus/handlers Title: Handlers Articles: - Url: nservicebus/handlers/accessing-data Title: Accessing data + - Url: nservicebus/handlers/convention-based + Title: Convention-based handlers - Url: nservicebus/handlers/handler-ordering Title: Handler Order + - Url: nservicebus/handlers/async-handlers + Title: Asynchronous Handlers - Url: nservicebus/sagas Title: Sagas Articles: diff --git a/nservicebus/handlers-and-sagas-registration.md b/nservicebus/handlers-and-sagas-registration.md new file mode 100644 index 00000000000..1d5ff20d449 --- /dev/null +++ b/nservicebus/handlers-and-sagas-registration.md @@ -0,0 +1,10 @@ +--- +title: Registering Handlers and Sagas +summary: How to register message handlers and sagas with an NServiceBus endpoint. +component: Core +reviewed: 2026-04-27 +--- + +Registration tells an endpoint which message handlers and sagas to include. NServiceBus supports explicit registration, recommended for new endpoints, and automatic discovery via assembly scanning, useful for plugin or dynamic discovery scenarios. + +partial: registration-content \ No newline at end of file diff --git a/nservicebus/handlers-and-sagas-registration_registration-content_core_[10,).partial.md b/nservicebus/handlers-and-sagas-registration_registration-content_core_[10,).partial.md new file mode 100644 index 00000000000..bc020d49c19 --- /dev/null +++ b/nservicebus/handlers-and-sagas-registration_registration-content_core_[10,).partial.md @@ -0,0 +1,115 @@ +## Source-generated registration (recommended) + +Starting in NServiceBus version 10.2, a source generation package can scan assemblies at build time and produce a strongly typed registration API. This keeps NServiceBus registrations componentized without requiring runtime assembly scanning. + +The generated API is composable: each scanned assembly produces extension methods that attach to a registry. For example, after referencing the source generator package, the registration code looks like this: + +```csharp +endpointConfiguration.Handlers.MyAssembly.MyNamespace.AddAll(); +``` + +Source-generated registration is trimming and AOT-friendly because it references handler and saga types directly from the composition root (the host). It also eliminates runtime surprises: any type that is discoverable at build time is discoverable at runtime with no additional scanning. + +### Default behavior + +Without the `[HandlerRegistryExtensions]` attribute, the source generator produces an entry point named after the assembly and creates registration methods from the discovered class names. The assembly name is sanitized into a valid C# identifier by removing non-alphanumeric characters, then `Assembly` is appended. For example, an assembly named `MyCompany.Shipping` produces `registry.Handlers.MyCompanyShippingAssembly...`, while `Shipping` produces `registry.Handlers.ShippingAssembly...`. + +| Type kind | Class name | Generated method | +|---|---|---| +| Handler | `OrderShippedHandler` | `AddOrderShippedHandler` | +| Handler | `OrderShipped` | `AddOrderShippedHandler` | +| Saga | `OrderShippingSaga` | `AddOrderShippingSaga` | +| Saga | `OrderShippingPolicy` | `AddOrderShippingPolicy` | + +For handlers, the generator prepends `Add` and guarantees the method name ends with `Handler`. If the class name does not already end with `Handler`, the suffix is appended automatically. For sagas, the generator prepends `Add` and ensures the name ends with `Saga`, except when the class already ends with `Saga` or `Policy` (case-insensitive). + +### Advanced source generation configuration + +The `[HandlerRegistryExtensions]` attribute can be applied to a `partial static class` to customize the source-generated handler registration API: + +#### `EntryPointName` + +Overrides the default assembly-based entry point name. The value must be a valid C# identifier. + +```csharp +[HandlerRegistryExtensions(EntryPointName = "Shipping")] +public static partial class RegistrationExtensions; +``` + +When the attribute above is applied, `registry.Handlers.Core...` becomes `registry.Handlers.Shipping...`. + +#### `RegistrationMethodNamePatterns` + +The default `Add` convention mirrors the class name exactly, which can produce repetitive or unnecessarily long method names. For example, `OrderShippedHandler` generates `AddOrderShippedHandler`, duplicating the `Handler` suffix on every call site. + +Use `RegistrationMethodNamePatterns` to remap class names to shorter or more idiomatic method names. Each pattern is a regex replacement in the form `pattern=>replacement`. The pattern is matched against the original class name, and the replacement string becomes the final method name, so any desired prefix must be included in the replacement itself. Patterns are evaluated in order and the first match wins. + +Invalid pattern format or regular expression syntax is caught by a build-time analyzer and reported as a compiler error. + +Examples: + +- `^(.*)Handler$=>Add$1` transforms `OrderShippedHandler` to `AddOrderShipped`. +- `Handler$=>Register` transforms `OrderShippedHandler` to `OrderShippedRegister`. +- `^(.*)Saga$=>Register$1Saga` transforms `OrderShippingSaga` to `RegisterOrderShippingSaga`. + +#### Visibility control + +The source generator automatically matches the visibility of the generated extension methods to the visibility of the attributed `partial class`. Declaring the class as `internal` hides the registration methods from the public API. + +### Relationship to other attributes + +`[HandlerRegistryExtensions]` works alongside `[Handler]` (for marking message handlers) and `[Saga]` (for marking sagas) to enable source generation. + +## Manual registration + +When source generation is not available or when only a few components need to be registered, individual types can be added explicitly. + +### Register a message handler + +Use `AddHandler()` to register a message handler: + +snippet: RegisterHandlerManually + +### Register a saga + +Use `AddSaga()` to register a saga: + +snippet: RegisterSagaManually + +### Enable a feature + +Use `EnableFeature()` to enable a feature: + +snippet: EnableFeatureManually + +### Register an installer + +Use `AddInstaller()` to register an installer: + +snippet: RegisterInstallerManually + +## Assembly scanning + +Automatic runtime discovery of handlers, sagas, features, and installers is performed by scanning assemblies. Assembly scanning is useful for plugin architectures, shared deployment directories, or other dynamic discovery scenarios. + +### Disable assembly scanning + +Assembly scanning can be completely disabled. When disabled, no assemblies are scanned, and all components must be explicitly registered. + +snippet: DisableAssemblyScanning + +When assembly scanning is disabled, message handlers, sagas, features, and installers must be explicitly registered. Messages received without a registered handler or saga [will fail and be moved to the error queue](/nservicebus/handlers/?version=core_10#no-handler-for-a-message). + +### Fine-grained scanning configuration + +Scanning can be configured with exclusions, additional paths, nested directories, and exception handling. See [Assembly scanning](/nservicebus/hosting/assembly-scanning.md) for all configuration options. + +## Hybrid approach + +Assembly scanning and manual registration can be combined. For example, scan for plugins in a shared directory and then explicitly register a set of core handlers. When scanning is disabled entirely, all components must be registered explicitly. + +## Choosing an approach + +- Prefer source-generated or manual explicit registration for new endpoints. +- Prefer assembly scanning when dynamic plugin discovery is required. +- Mixed mode is valid when gradual migration is needed. diff --git a/nservicebus/handlers-and-sagas-registration_registration-content_core_[9,10).partial.md b/nservicebus/handlers-and-sagas-registration_registration-content_core_[9,10).partial.md new file mode 100644 index 00000000000..408b09e282b --- /dev/null +++ b/nservicebus/handlers-and-sagas-registration_registration-content_core_[9,10).partial.md @@ -0,0 +1,3 @@ +In NServiceBus version 9 and earlier, handlers and sagas are registered automatically via [assembly scanning](/nservicebus/hosting/assembly-scanning.md). No explicit registration is required — the endpoint discovers handler and saga types by scanning assemblies at startup. + +See [assembly scanning](/nservicebus/hosting/assembly-scanning.md) for configuration options including how to exclude assemblies or disable scanning entirely. \ No newline at end of file diff --git a/nservicebus/handlers-and-sagas.md b/nservicebus/handlers-and-sagas.md index 49caa0a915f..479f8b1751f 100644 --- a/nservicebus/handlers-and-sagas.md +++ b/nservicebus/handlers-and-sagas.md @@ -2,7 +2,7 @@ title: Handlers and Sagas summary: A brief introduction to handlers and sagas component: Core -reviewed: 2025-02-19 +reviewed: 2026-04-27 related: - nservicebus/handlers - nservicebus/sagas @@ -11,12 +11,12 @@ related: There are two standard ways of executing code when a message is processed: [handlers](handlers/) and [sagas](sagas/). -Handler instances are instantiated on a per-message basis, executed, and then disposed of. These are sometimes referred to as “stateless handlers”. +Handler instances are instantiated on a per-message basis, executed, and then disposed of. These are sometimes referred to as "stateless handlers". -Saga instances are also instantiated on a per-message basis, executed, and then disposed of. However they differ from handlers in that, once instantiated, they are passed an instance of a "Data" class. The "Saga Data" is persistent state that is shared between a given saga type based on a key. These are sometimes referred to as “stateful handlers”. +Saga instances are also instantiated on a per-message basis, executed, and then disposed of. However they differ from handlers in that, once instantiated, they are passed an instance of a "Data" class. The "Saga Data" is persistent state that is shared between a given saga type based on a key. These are sometimes referred to as "stateful handlers". Other concepts that both handlers and sagas share: * [Recoverability](/nservicebus/recoverability/) (i.e. what happens when message processing fails) * Executed within the same [pipeline](/nservicebus/pipeline) - * Detected via [assembly scanning](/nservicebus/hosting/assembly-scanning.md) + * Registered via [handler and saga registration](handlers-and-sagas-registration.md) \ No newline at end of file diff --git a/nservicebus/handlers/convention-based.md b/nservicebus/handlers/convention-based.md new file mode 100644 index 00000000000..a58cd79159f --- /dev/null +++ b/nservicebus/handlers/convention-based.md @@ -0,0 +1,83 @@ +--- +title: Convention-based handlers +summary: How to create message handlers that don't implement IHandleMessages +component: Core +versions: '[10,)' +reviewed: 2026-05-04 +related: +--- + +Starting with NServiceBus version 10.2.0, NServiceBus supports **convention-based message handlers** that do not implement `IHandleMessages`, enabling handlers to be expressed like this: + +snippet: ConventionHandlersTldrSample + +And then registered on the endpoint like this: + +snippet: ConventionHandlerAddAllFromAssembly + +Convention-based handlers are not discovered through traditional assembly scanning, but instead are either added to an NServiceBus endpoint declaratively, or with help from Roslyn analyzers and source generators. + +## Handler structure + +A convention-based handler can look exactly like a regular message handler, but does not implement the interface: + +snippet: SimpleConventionBasedHandler + +Without the rigid structure of the `IHandleMessages` interface, additional parameters can be added to the `Handle` method: + +snippet: ConventionsBasedHandlerExtraParams + +These requirements must be met for a class to be recognized as a convention-based message handler: + +- Must contain a handler method named `Handle` which returns `Task`. +- The handler method's first parameter must be a message class. +- The handler method's second parameter must be an `IMessageHandlerContext`. +- After the first two parameters, any additional parameters must be either a `CancellationToken` or Services registered in the host's `IServiceCollection`. +- It can be an instance or static method. +- A handler class may contain multiple handler methods, differing by the message type, but these methods become an inseparable unit. It is not possible to register one handler method on a class but not the other. +- If multiple handler methods use the same message type as the first parameter, they will all be executed on the same message. + +## Registering handlers + +Because handlers not using a marker interface cannot be found by assembly scanning, they must be added to the endpoint. This can be done manually: + +snippet: ConventionHandlerRegistrationWithoutAttribute + +However, decorating a handler class with the `NServiceBus.HandlerAttribute` (or `NServiceBus.SagaAttribute` for [sagas](/nservicebus/sagas/)) enables source generation that enables all decorated handlers and/or sagas in an entire project to be added with one line of configuration. + +First, decorate handlers with `[Handler]`, or sagas with `[Saga]`: + +snippet: DecoratedConventionHandler + +This generates source code that allows all handlers and sagas from an assembly to be registered at once: + +snippet: ConventionHandlerAddAllFromAssembly + +However, the generated source is flexible and allows registering just all handlers, just all sagas, or both from any level of the namespace hierarchy, or at the top level of the assembly: + +snippet: ConventionHandlerAllGeneratedAddMethods + +## Analyzers + +While the source generation simplifies registering multiple handlers or sagas to an endpoint with one line of code, the generation relies on the `[Handler]` and `[Saga]` attributes to identify what qualifies as a handler or a saga. + +> [!TIP] +> The reason the source generation works on the `[Handler]` and `[Saga]` attributes is because source generators, which may run in your editor up to every time you press a key, must be very fast and efficient. Identifying generation targets using a marker attribute is the most optimized method available when using the Roslyn SDK. On the other hand, using marker interfaces to identify generation targets is [explicitly called out as an anti-pattern in the source generator documentation](https://github.com/dotnet/roslyn/blob/main/docs/features/incremental-generators.cookbook.md). + +Roslyn analyzers help to ensure that handlers or sagas don't accidentally escape identification, causing them to remain unregistered accidentally: + +- **NSB0034**: Mark convention-based handlers with HandlerAttribute to enable source generation +- **NSB0025**: Mark sagas with SagaAttribute to enable source generation + +These diagnostics default to `DiagnosticSeverity.Info` but can be upgraded to ensure handlers and sagas are not missed. + +The following `.editorconfig` settings will upgrade both diagnostics to errors so that the build will fail if the attributes are not added: + +```ini +[*.cs] + +# Ensure message handlers are decorated with [Handler] to enable source generation +dotnet_diagnostic.NSB0034.severity = error +# Ensure sagas are decorated with [Saga] to enable source generation +dotnet_diagnostic.NSB0034.severity = error +``` \ No newline at end of file diff --git a/nservicebus/handlers/index.md b/nservicebus/handlers/index.md index c0f4ae783ce..7a44eb9f388 100644 --- a/nservicebus/handlers/index.md +++ b/nservicebus/handlers/index.md @@ -2,7 +2,7 @@ title: Handlers summary: Write a class to handle messages in NServiceBus. component: Core -reviewed: 2026-01-19 +reviewed: 2026-04-27 redirects: - nservicebus/how-do-i-handle-a-message --- @@ -62,7 +62,7 @@ If the original message is not published as an event, but rather [sent](/nservic - Send a copy of the original message to each endpoint. - This provides the greatest degree of isolation and provides more granularity for retry policy customization and scaling, greater visibility, better monitoring, and other benefits. -partial: manual-registration +By default, message handlers are discovered via assembly scanning. They can also be registered explicitly. See [Registering Handlers and Sagas](/nservicebus/handlers-and-sagas-registration.md) for all registration options. ## Unit testing diff --git a/nservicebus/handlers/index_manual-registration_core_[10,).partial.md b/nservicebus/handlers/index_manual-registration_core_[10,).partial.md deleted file mode 100644 index ed234261a11..00000000000 --- a/nservicebus/handlers/index_manual-registration_core_[10,).partial.md +++ /dev/null @@ -1,5 +0,0 @@ -## Manual handler registration - -By default, message handlers are automatically discovered through [assembly scanning](/nservicebus/hosting/assembly-scanning.md?version=core_10). When [assembly scanning is disabled](/nservicebus/hosting/assembly-scanning.md?version=core_10#disable-assembly-scanning), handlers must be manually registered using `AddHandler()`: - -snippet: RegisterHandlerManually diff --git a/nservicebus/hosting/assembly-scanning.md b/nservicebus/hosting/assembly-scanning.md index bca33d2e398..75895e0a8e2 100644 --- a/nservicebus/hosting/assembly-scanning.md +++ b/nservicebus/hosting/assembly-scanning.md @@ -1,7 +1,7 @@ --- title: Assembly scanning summary: To enable the automatic detection of various features, NServiceBus scans assemblies for well-known types -reviewed: 2024-10-24 +reviewed: 2026-04-27 component: core redirects: - nservicebus/assembly-scanning @@ -9,6 +9,9 @@ redirects: NServiceBus scans assemblies at endpoint startup to automatically detect and load [message types](/nservicebus/messaging/messages-events-commands.md), [message handlers](/nservicebus/handlers/), [features](/nservicebus/pipeline/features.md), and [installers](/nservicebus/operations/installers.md). +> [!NOTE] +> Assembly scanning is optional starting in NServiceBus version 10.2. For the modern explicit registration approaches, see [Registering Handlers and Sagas](/nservicebus/handlers-and-sagas-registration.md). + There are some cases where finer control over which assemblies are loaded is required: * To limit the number of assemblies being scanned and hence improve startup time. diff --git a/nservicebus/hosting/assembly-scanning_disable-assembly-scanning_core_[10,).partial.md b/nservicebus/hosting/assembly-scanning_disable-assembly-scanning_core_[10,).partial.md index 9100b2abd39..5d3806ac861 100644 --- a/nservicebus/hosting/assembly-scanning_disable-assembly-scanning_core_[10,).partial.md +++ b/nservicebus/hosting/assembly-scanning_disable-assembly-scanning_core_[10,).partial.md @@ -6,6 +6,8 @@ snippet: DisableAssemblyScanning > [!WARNING] > When assembly scanning is disabled, message handlers, sagas, features, and installers must be explicitly registered. Messages received without a registered handler or saga [will fail and be moved to the error queue](/nservicebus/handlers/?version=core_10#no-handler-for-a-message). +> +> See [Registering Handlers and Sagas](/nservicebus/handlers-and-sagas-registration.md) for details on explicit registration approaches. > [!NOTE] > Manual registration APIs work alongside assembly scanning, enabling a hybrid approach. Use [assembly exclusion options](#assemblies-to-scan) to limit what gets scanned, then manually register specific components as needed. diff --git a/nservicebus/hosting/index.md b/nservicebus/hosting/index.md index 91434c3853d..5a259cdec22 100644 --- a/nservicebus/hosting/index.md +++ b/nservicebus/hosting/index.md @@ -25,7 +25,6 @@ The [Microsoft Generic Host](https://docs.microsoft.com/en-us/aspnet/core/fundam * Configuration * [Logging](/nservicebus/logging) * [Dependency injection](/nservicebus/dependency-injection/) - * [Startup and Shutdown](/samples/startup-shutdown-sequence/) * [Endpoint Lifecycle](/nservicebus/lifecycle/) * [Critical Error handling](critical-errors.md) diff --git a/nservicebus/hosting/web-application.md b/nservicebus/hosting/web-application.md index 6cdd3d92d75..44e62a68206 100644 --- a/nservicebus/hosting/web-application.md +++ b/nservicebus/hosting/web-application.md @@ -6,7 +6,6 @@ isLearningPath: true related: - samples/web - nservicebus/lifecycle - - samples/startup-shutdown-sequence - nservicebus/messaging/callbacks - nservicebus/hosting/publishing-from-web-applications --- diff --git a/nservicebus/hosting/windows-service.md b/nservicebus/hosting/windows-service.md index 9f3eb72e58a..f94c13d755e 100644 --- a/nservicebus/hosting/windows-service.md +++ b/nservicebus/hosting/windows-service.md @@ -7,7 +7,6 @@ isLearningPath: true related: - nservicebus/dotnet-templates - nservicebus/lifecycle - - samples/startup-shutdown-sequence - samples/hosting/generic-host --- diff --git a/nservicebus/lifecycle/endpointstartandstop.md b/nservicebus/lifecycle/endpointstartandstop.md index b083aad35b0..5b396453547 100644 --- a/nservicebus/lifecycle/endpointstartandstop.md +++ b/nservicebus/lifecycle/endpointstartandstop.md @@ -3,8 +3,6 @@ title: When Endpoint Instance Starts and Stops summary: How to hook into the startup and shutdown sequence of an endpoint instance. reviewed: 2025-07-22 component: core -related: - - samples/startup-shutdown-sequence redirects: - nservicebus/lifecycle/iwanttorunwhenbusstartsandstops --- diff --git a/nservicebus/lifecycle/ineedinitialization.md b/nservicebus/lifecycle/ineedinitialization.md index 734337700da..4666a126755 100644 --- a/nservicebus/lifecycle/ineedinitialization.md +++ b/nservicebus/lifecycle/ineedinitialization.md @@ -3,8 +3,6 @@ title: Custom Endpoint Initialization summary: Implement INeedInitialization to hook into the very beginning of the endpoint creation sequence of NServiceBus. component: Core reviewed: 2026-05-05 -related: - - samples/startup-shutdown-sequence --- Classes that implement `NServiceBus.INeedInitialization` are created and called as one of the first steps performed during endpoint creation. Use `INeedInitialization` to register custom endpoint configuration logic. diff --git a/nservicebus/lifecycle/iwanttorunbeforeconfigurationisfinalized.md b/nservicebus/lifecycle/iwanttorunbeforeconfigurationisfinalized.md index 7d0fb1b48ee..38147332718 100644 --- a/nservicebus/lifecycle/iwanttorunbeforeconfigurationisfinalized.md +++ b/nservicebus/lifecycle/iwanttorunbeforeconfigurationisfinalized.md @@ -4,8 +4,6 @@ summary: An interface that allows hooking into the configuration sequence of NSe component: Core versions: '[,10)' reviewed: 2026-01-09 -related: - - samples/startup-shutdown-sequence --- > [!CAUTION] diff --git a/nservicebus/logging/index.md b/nservicebus/logging/index.md index e611524895c..2d6e1f22117 100644 --- a/nservicebus/logging/index.md +++ b/nservicebus/logging/index.md @@ -12,6 +12,8 @@ related: - samples/logging --- +partial: modern + ## Default logging NServiceBus has a built-in logging mechanism that does not depend on any external libraries. While limited in terms of available log targets, this built-in mechanism is production-ready and offers defaults that are reasonable for most deployments. The built-in framework is available and used as default in all NServiceBus hosting modes. Regardless of whether the built-in logging or a custom logging library is used under the hood, the NServiceBus logging abstractions can be used for writing log messages in user code. By default NServiceBus has three log targets configured: diff --git a/nservicebus/logging/index_modern_core_[10,).partial.md b/nservicebus/logging/index_modern_core_[10,).partial.md new file mode 100644 index 00000000000..0f618321627 --- /dev/null +++ b/nservicebus/logging/index_modern_core_[10,).partial.md @@ -0,0 +1,39 @@ +NServiceBus endpoints integrate with the standard .NET logging infrastructure. [Microsoft.Extensions.Logging](https://learn.microsoft.com/en-us/dotnet/core/extensions/logging/) provides rich filtering, structured logging, and [works seamlessly with ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/), the Generic Host, and many third-party providers. + + +## Using `ILogger` in handlers + +The recommended way to write log entries inside message handlers is to inject `ILogger` through the constructor: + +snippet: InjectingILoggerInterface + +`ILogger` is automatically wired into the dependency injection container when hosting with the .NET Generic Host. + +## Configuring the default rolling file logger + +When no external logging providers are registered, NServiceBus supplies backward-compatible defaults: a colored console provider and a rolling file provider. Consider registering standard [Microsoft logging providers](https://learn.microsoft.com/en-us/dotnet/core/extensions/logging/providers) such as Console, Debug, or EventLog for new applications. + +If continuing with the built-in NServiceBus providers, configure the rolling file logger through `RollingLoggerProviderOptions`: + +snippet: ConfiguringRollingFileLogger + +When external logging providers are added to the host, the built-in providers automatically disable themselves so the external configuration takes over without any manual opt-out. + +## Using custom logging providers + +Register custom logging frameworks directly with the `Microsoft.Extensions.Logging` infrastructure on the host: + +```csharp +var builder = Host.CreateApplicationBuilder(); + +builder.Logging.AddSerilog(); +``` + +## High-performance logging + +For scenarios that require minimal allocations, use the [`LoggerMessage`](https://learn.microsoft.com/en-us/dotnet/core/extensions/loggermessage-generator) source generator: + +snippet: UsingLoggerMessageSourceGenerator + +> [!WARNING] +> The NServiceBus-specific logging APIs described in the next section below are still functional but produce obsolete warnings starting in version 10.2 and will be removed in version 12. Use the `Microsoft.Extensions.Logging` patterns shown earlier for new development. diff --git a/nservicebus/operations/installers_installer-api_core_[10,).partial.md b/nservicebus/operations/installers_installer-api_core_[10,).partial.md new file mode 100644 index 00000000000..364a5ddb41b --- /dev/null +++ b/nservicebus/operations/installers_installer-api_core_[10,).partial.md @@ -0,0 +1,10 @@ +## Running installers + +When requiring special privileges to setup the endpoint, the installer API can be used to run all necessary installation steps: + +snippet: installer-setup + +> [!NOTE] +> The installer APIs always run installers, regardless of whether the endpoint has configured `EnableInstallers`. + +The installer APIs are intended to be used when resources required by the endpoint must be set up with different privileges than the endpoint itself requires. To setup the endpoint as part of the endpoint host process, see the [Running installers during endpoint startup](#running-installers-during-endpoint-startup) article. diff --git a/nservicebus/operations/installers_installer-api_core_[8,).partial.md b/nservicebus/operations/installers_installer-api_core_[8,10).partial.md similarity index 100% rename from nservicebus/operations/installers_installer-api_core_[8,).partial.md rename to nservicebus/operations/installers_installer-api_core_[8,10).partial.md diff --git a/nservicebus/pipeline/features.md b/nservicebus/pipeline/features.md index 7225a6735bb..9a3d16152a9 100644 --- a/nservicebus/pipeline/features.md +++ b/nservicebus/pipeline/features.md @@ -7,7 +7,6 @@ versions: '[5.0,)' related: - samples/feature - samples/header-manipulation - - samples/startup-shutdown-sequence --- While NServiceBus provides interfaces to plug in code at certain steps in the lifecycle, Features offer a more complete approach to writing and distributing custom extensions. diff --git a/nservicebus/sagas/index.md b/nservicebus/sagas/index.md index b2eb4614f4a..8d48f144b0d 100644 --- a/nservicebus/sagas/index.md +++ b/nservicebus/sagas/index.md @@ -2,7 +2,7 @@ title: Sagas summary: Master NServiceBus sagas to coordinate distributed workflows and ensure reliable long-running processes. component: Core -reviewed: 2026-01-23 +reviewed: 2026-04-27 redirects: - nservicebus/sagas-in-nservicebus related: @@ -50,6 +50,9 @@ partial: disable-shared-state-check > [!NOTE] > If a saga property is a [record type](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/record), that record type must be mutable so it can be deserialized. +> [!NOTE] +> By default, sagas are discovered via assembly scanning. They can also be registered explicitly. See [Registering Handlers and Sagas](/nservicebus/handlers-and-sagas-registration.md) for all registration options. + ## Adding behavior The important part of a long-running process is its behavior. Just like regular message handlers, the behavior of a saga is implemented via the `IHandleMessages` interface for the message types to be handled. @@ -212,5 +215,3 @@ Saga state is read immediately before a message processing method is invoked, an - Saga state reads and writes do not occur during a stage. They occur during invocation in the `Invoke Handlers` stage and cannot be intercepted. If multiple saga types are invoked for the same message, each read, invoke, write cycle will occur sequentially, for each saga type. - -partial: manual-registration diff --git a/nservicebus/sagas/index_manual-registration_core_[10,).partial.md b/nservicebus/sagas/index_manual-registration_core_[10,).partial.md deleted file mode 100644 index e0cfd8e04db..00000000000 --- a/nservicebus/sagas/index_manual-registration_core_[10,).partial.md +++ /dev/null @@ -1,6 +0,0 @@ -## Manual saga registration - -By default, sagas are automatically discovered through [assembly scanning](/nservicebus/hosting/assembly-scanning.md?version=core_10). When [assembly scanning is disabled](/nservicebus/hosting/assembly-scanning.md?version=core_10#disable-assembly-scanning), sagas must be manually registered using `AddSaga()`: - -snippet: RegisterSagaManually - diff --git a/nservicebus/upgrades/4to5.md b/nservicebus/upgrades/4to5.md index d16c5421d31..94eecb45eeb 100644 --- a/nservicebus/upgrades/4to5.md +++ b/nservicebus/upgrades/4to5.md @@ -254,7 +254,7 @@ To move over to this NuGet after updating to version 5: For more details refer to the following GitHub issue: https://github.com/Particular/NServiceBus/issues/1605 #### 1. Install the NServiceBus.RavenDB NuGet package - + `Install-Package NServiceBus.RavenDB` #### 2. Use the new configuration API @@ -293,7 +293,7 @@ Old Profile | New Profile `NServiceBus.Master` | `NServiceBus.MsmqMaster` `NServiceBus.Worker` | `NServiceBus.MsmqWorker` -## Obsolete the IWantToRunBeforeConfiguration API +## Obsolete the IWantToRunBeforeConfiguration API The `IWantToRunBeforeConfiguration` API is no longer needed and is obsolete. The replacement is to use either `INeedInitalization` or use a [feature](/nservicebus/pipeline/features.md) where a `Default(s=>..)` can be setup in the constructor of the feature. @@ -574,7 +574,7 @@ busConfiguration.DefineCriticalErrorAction( (message, exception) => { ... - }); + }); ``` For more details refer to the following GitHub issue: https://github.com/Particular/NServiceBus/issues/2254 @@ -614,7 +614,7 @@ For more details refer to the following GitHub issue: https://github.com/Particu // --- NServiceBus 5.x --- busConfiguration.LicensePath("PathToLicense"); - + ``` ```cs @@ -713,7 +713,7 @@ busConfiguration.UsePersistence(); // configure.EnablePerformanceCounters(); // configure.SetEndpointSLA(TimeSpan.FromMinutes(3)); -// --- NServiceBus 5.x --- +// --- NServiceBus 5.x --- busConfiguration.EnableSLAPerformanceCounter(); // or busConfiguration.EnableSLAPerformanceCounter(TimeSpan.FromMinutes(3)); @@ -755,7 +755,7 @@ public class BusInstance : public static IBuilder Builder; public static IBus Bus; - + ... } ``` @@ -822,8 +822,6 @@ public class PrincipalMutator : } ``` -Another option is to use a custom header as illustrated in the [Appending username using headers](/samples/username-header/) sample. - ## INeedToInstallInfrastructure The interface `INeedToInstallInfrastructure` has been removed. diff --git a/nservicebus/upgrades/5to6/messaging.md b/nservicebus/upgrades/5to6/messaging.md index b7b2ab0de48..d7d8a1a5e83 100644 --- a/nservicebus/upgrades/5to6/messaging.md +++ b/nservicebus/upgrades/5to6/messaging.md @@ -18,8 +18,6 @@ In NServiceBus version 6, custom [correlation IDs](/nservicebus/messaging/header The `WinIdName` existed to enable the Principal Replacement feature (`RunHandlersUnderIncomingPrincipal` in NServiceBus version 4 and `ImpersonateSender` in version 3). -See the [appending username using headers](/samples/username-header/) sample for usage of this API. - This feature was removed in version 5 and the `WinIdName` header will no longer be added to outgoing messages. To re-add this header to outgoing messages a [mutator](/nservicebus/pipeline/message-mutators.md) can be used. @@ -37,9 +35,6 @@ public class WinIdNameMutator : } ``` -Another option is to use a custom header as illustrated in the [appending username using headers](/samples/username-header/) sample. - - ## Throttling Requirements for throttling mechanisms are very different. While some third-party services (e.g. GitHub, Twitter, Google) enforce rate limits on certain time periods, other services may have entirely different usage limitations. The throttling API in NServiceBus version 5 offers a limited, messages-per-second-based throttling mechanism which works for very few scenarios. Therefore, the throttling API has been removed with version 6 without a built-in alternative. diff --git a/samples/aws/cloud-events/Sqs_9/Endpoint/Endpoint.csproj b/samples/aws/cloud-events/Sqs_9/Endpoint/Endpoint.csproj index 6e4ffe2fa22..6bb25491cdc 100644 --- a/samples/aws/cloud-events/Sqs_9/Endpoint/Endpoint.csproj +++ b/samples/aws/cloud-events/Sqs_9/Endpoint/Endpoint.csproj @@ -11,6 +11,7 @@ + \ No newline at end of file diff --git a/samples/aws/lambda-sqs-annotations/SQSLambda_4/Messages/Messages.csproj b/samples/aws/lambda-sqs-annotations/SQSLambda_4/Messages/Messages.csproj index 10269b37bf3..a83d3c6f21e 100644 --- a/samples/aws/lambda-sqs-annotations/SQSLambda_4/Messages/Messages.csproj +++ b/samples/aws/lambda-sqs-annotations/SQSLambda_4/Messages/Messages.csproj @@ -7,7 +7,7 @@ - + \ No newline at end of file diff --git a/samples/aws/lambda-sqs-annotations/SQSLambda_4/RegularEndpoint/Program.cs b/samples/aws/lambda-sqs-annotations/SQSLambda_4/RegularEndpoint/Program.cs index e3acd6228ac..01c724c0b34 100644 --- a/samples/aws/lambda-sqs-annotations/SQSLambda_4/RegularEndpoint/Program.cs +++ b/samples/aws/lambda-sqs-annotations/SQSLambda_4/RegularEndpoint/Program.cs @@ -1,11 +1,18 @@ -Console.Title = "RegularEndpoint"; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +Console.Title = "RegularEndpoint"; var endpointConfiguration = new EndpointConfiguration("RegularEndpoint"); endpointConfiguration.UseSerialization(); endpointConfiguration.UseTransport(); -var endpointInstance = await Endpoint.Start(endpointConfiguration); +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +var host = builder.Build(); +var messageSession = host.Services.GetRequiredService(); +await host.StartAsync(); Console.WriteLine("Press [ENTER] to send a message to the serverless endpoint queue."); Console.WriteLine("Press [Esc] to exit."); @@ -17,11 +24,11 @@ switch (key.Key) { case ConsoleKey.Enter: - await endpointInstance.Send("ServerlessEndpoint", new TriggerMessage()); + await messageSession.Send("ServerlessEndpoint", new TriggerMessage()); Console.WriteLine("Message sent to the serverless endpoint queue."); break; case ConsoleKey.Escape: - await endpointInstance.Stop(); + await host.StopAsync(); return; } } \ No newline at end of file diff --git a/samples/aws/lambda-sqs-annotations/SQSLambda_4/ServerlessEndpoint/serverless.template b/samples/aws/lambda-sqs-annotations/SQSLambda_4/ServerlessEndpoint/serverless.template index 0dea8d356bd..60bd5ef3b75 100644 --- a/samples/aws/lambda-sqs-annotations/SQSLambda_4/ServerlessEndpoint/serverless.template +++ b/samples/aws/lambda-sqs-annotations/SQSLambda_4/ServerlessEndpoint/serverless.template @@ -1,7 +1,7 @@ { "AWSTemplateFormatVersion": "2010-09-09", "Transform": "AWS::Serverless-2016-10-31", - "Description": "Template that creates an SQS queue and a function that is invoked when a new message arrives. This template is partially managed by Amazon.Lambda.Annotations (v1.8.0.0).", + "Description": "Template that creates an SQS queue and a function that is invoked when a new message arrives. This template is partially managed by Amazon.Lambda.Annotations (v1.15.1.0).", "Resources": { "ErrorQueue": { "Properties": { diff --git a/samples/aws/sagas/DynamoDB_4/ClientUI/ClientUI.csproj b/samples/aws/sagas/DynamoDB_4/ClientUI/ClientUI.csproj index b4ecc15c4eb..54620dac9e1 100644 --- a/samples/aws/sagas/DynamoDB_4/ClientUI/ClientUI.csproj +++ b/samples/aws/sagas/DynamoDB_4/ClientUI/ClientUI.csproj @@ -14,7 +14,6 @@ - diff --git a/samples/aws/sagas/DynamoDB_4/ClientUI/Program.cs b/samples/aws/sagas/DynamoDB_4/ClientUI/Program.cs index bb73da1f162..1efdb80c968 100644 --- a/samples/aws/sagas/DynamoDB_4/ClientUI/Program.cs +++ b/samples/aws/sagas/DynamoDB_4/ClientUI/Program.cs @@ -1,4 +1,7 @@ -var endpointConfiguration = new EndpointConfiguration("Samples.DynamoDB.Lambda.ClientUI"); +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +var endpointConfiguration = new EndpointConfiguration("Samples.DynamoDB.Lambda.ClientUI"); endpointConfiguration.UseSerialization(); endpointConfiguration.SendFailedMessagesTo("Samples-DynamoDB-Lambda-Error"); @@ -6,7 +9,11 @@ var routing = transport.Routing(); routing.RouteToEndpoint(typeof(PlaceOrder), "Samples.DynamoDB.Lambda.Sales"); -var endpoint = await Endpoint.Start(endpointConfiguration); +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +var host = builder.Build(); +var messageSession = host.Services.GetRequiredService(); +await host.StartAsync(); Console.WriteLine(); Console.WriteLine("Press [Enter] to place an order. Press [Esc] to quit."); @@ -20,14 +27,14 @@ case ConsoleKey.Enter: { var orderId = Guid.NewGuid().ToString("N"); - await endpoint.Send(new PlaceOrder() { OrderId = orderId }); + await messageSession.Send(new PlaceOrder() { OrderId = orderId }); Console.WriteLine($"Order {orderId} was placed."); break; } case ConsoleKey.Escape: { - await endpoint.Stop(); + await host.StopAsync(); return; } } diff --git a/samples/aws/sagas/DynamoDB_4/Messages/Messages.csproj b/samples/aws/sagas/DynamoDB_4/Messages/Messages.csproj index 57c3e0efa4b..693cb90a2e2 100644 --- a/samples/aws/sagas/DynamoDB_4/Messages/Messages.csproj +++ b/samples/aws/sagas/DynamoDB_4/Messages/Messages.csproj @@ -7,7 +7,7 @@ - + diff --git a/samples/aws/sqs-simple/Sqs_9/Receiver/Program.cs b/samples/aws/sqs-simple/Sqs_9/Receiver/Program.cs index 3e25f300118..f61ce5d03eb 100644 --- a/samples/aws/sqs-simple/Sqs_9/Receiver/Program.cs +++ b/samples/aws/sqs-simple/Sqs_9/Receiver/Program.cs @@ -19,5 +19,5 @@ Console.ReadKey(); Console.WriteLine("Starting..."); -builder.UseNServiceBus(endpointConfiguration); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); await builder.Build().RunAsync(); diff --git a/samples/aws/sqs-simple/Sqs_9/Receiver/Receiver.csproj b/samples/aws/sqs-simple/Sqs_9/Receiver/Receiver.csproj index b8ba53f8699..9313cc9bb90 100644 --- a/samples/aws/sqs-simple/Sqs_9/Receiver/Receiver.csproj +++ b/samples/aws/sqs-simple/Sqs_9/Receiver/Receiver.csproj @@ -13,7 +13,6 @@ - \ No newline at end of file diff --git a/samples/aws/sqs-simple/Sqs_9/Sender/Program.cs b/samples/aws/sqs-simple/Sqs_9/Sender/Program.cs index e85f08f9f00..4e915fb094f 100644 --- a/samples/aws/sqs-simple/Sqs_9/Sender/Program.cs +++ b/samples/aws/sqs-simple/Sqs_9/Sender/Program.cs @@ -1,3 +1,6 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + Console.Title = "SimpleSender"; #region ConfigureEndpoint @@ -17,11 +20,15 @@ routing.RouteToEndpoint(typeof(MyCommand), "Samples.Sqs.SimpleReceiver"); endpointConfiguration.EnableInstallers(); -var endpointInstance = await Endpoint.Start(endpointConfiguration); +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +var host = builder.Build(); +var messageSession = host.Services.GetRequiredService(); +await host.StartAsync(); -await SendMessages(endpointInstance); +await SendMessages(messageSession); -await endpointInstance.Stop(); +await host.StopAsync(); static async Task SendMessages(IMessageSession messageSession) { diff --git a/samples/aws/sqs-simple/Sqs_9/Shared/Shared.csproj b/samples/aws/sqs-simple/Sqs_9/Shared/Shared.csproj index ebc4c9bc1a3..f47df022a81 100644 --- a/samples/aws/sqs-simple/Sqs_9/Shared/Shared.csproj +++ b/samples/aws/sqs-simple/Sqs_9/Shared/Shared.csproj @@ -7,7 +7,7 @@ - + \ No newline at end of file diff --git a/samples/azure-functions/service-bus-kafka/ASBS_6/AzureFunctions.KafkaTrigger.FunctionsHostBuilder/Program.cs b/samples/azure-functions/service-bus-kafka/ASBS_6/AzureFunctions.KafkaTrigger.FunctionsHostBuilder/Program.cs index 25cd8bc1509..a06764b700d 100644 --- a/samples/azure-functions/service-bus-kafka/ASBS_6/AzureFunctions.KafkaTrigger.FunctionsHostBuilder/Program.cs +++ b/samples/azure-functions/service-bus-kafka/ASBS_6/AzureFunctions.KafkaTrigger.FunctionsHostBuilder/Program.cs @@ -17,10 +17,7 @@ routing.RouteToEndpoint(typeof(FollowUp), "Samples.KafkaTrigger.ConsoleEndpoint"); -var endpoint = await Endpoint.Start(cfg); - -// Inject the endpoint in the DI container -builder.Services.AddSingleton(endpoint); +builder.Services.AddNServiceBusEndpoint(cfg); var host = builder.Build(); diff --git a/samples/azure-functions/service-bus-kafka/ASBS_6/AzureFunctions.Messages/AzureFunctions.Messages.csproj b/samples/azure-functions/service-bus-kafka/ASBS_6/AzureFunctions.Messages/AzureFunctions.Messages.csproj index afb41271b56..5bf55bdca71 100644 --- a/samples/azure-functions/service-bus-kafka/ASBS_6/AzureFunctions.Messages/AzureFunctions.Messages.csproj +++ b/samples/azure-functions/service-bus-kafka/ASBS_6/AzureFunctions.Messages/AzureFunctions.Messages.csproj @@ -6,7 +6,7 @@ - + \ No newline at end of file diff --git a/samples/azure-functions/service-bus-kafka/ASBS_6/ConsoleEndpoint/Program.cs b/samples/azure-functions/service-bus-kafka/ASBS_6/ConsoleEndpoint/Program.cs index ca295046510..f4328eacb62 100644 --- a/samples/azure-functions/service-bus-kafka/ASBS_6/ConsoleEndpoint/Program.cs +++ b/samples/azure-functions/service-bus-kafka/ASBS_6/ConsoleEndpoint/Program.cs @@ -1,5 +1,7 @@ using AzureFunctions.Messages.KafkaMessages; using Confluent.Kafka; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; const string endpointName = "Samples.KafkaTrigger.ConsoleEndpoint"; Console.Title = endpointName; @@ -17,7 +19,10 @@ var transport = new AzureServiceBusTransport(connectionString, TopicTopology.Default); endpointConfiguration.UseTransport(transport); -var endpointInstance = await Endpoint.Start(endpointConfiguration); +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +var host = builder.Build(); +await host.StartAsync(); var config = new ProducerConfig { @@ -62,4 +67,4 @@ } } -await endpointInstance.Stop(); \ No newline at end of file +await host.StopAsync(); \ No newline at end of file diff --git a/samples/azure-service-bus-netstandard/cloud-events/ASBS_6/Endpoint/Endpoint.csproj b/samples/azure-service-bus-netstandard/cloud-events/ASBS_6/Endpoint/Endpoint.csproj index 8f7a336f661..c76bff28bfa 100644 --- a/samples/azure-service-bus-netstandard/cloud-events/ASBS_6/Endpoint/Endpoint.csproj +++ b/samples/azure-service-bus-netstandard/cloud-events/ASBS_6/Endpoint/Endpoint.csproj @@ -9,5 +9,6 @@ + \ No newline at end of file diff --git a/samples/azure-service-bus-netstandard/native-integration-pub-sub/ASBS_6/Publisher/Program.cs b/samples/azure-service-bus-netstandard/native-integration-pub-sub/ASBS_6/Publisher/Program.cs index 1c9a90a6e7e..117adc001cc 100644 --- a/samples/azure-service-bus-netstandard/native-integration-pub-sub/ASBS_6/Publisher/Program.cs +++ b/samples/azure-service-bus-netstandard/native-integration-pub-sub/ASBS_6/Publisher/Program.cs @@ -1,5 +1,7 @@ using System; using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NServiceBus; Console.Title = "Publisher"; @@ -20,18 +22,23 @@ var transport = new AzureServiceBusTransport(connectionString, TopicTopology.Default); endpointConfiguration.UseTransport(transport); -var endpointInstance = await Endpoint.Start(endpointConfiguration); +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +var host = builder.Build(); +var messageSession = host.Services.GetRequiredService(); +await host.StartAsync(); + Console.WriteLine("Press any key to publish events"); Console.ReadKey(); Console.WriteLine(); -await endpointInstance.Publish(new EventOne +await messageSession.Publish(new EventOne { Content = $"{nameof(EventOne)} sample content", PublishedOnUtc = DateTime.UtcNow }); -await endpointInstance.Publish(new EventTwo +await messageSession.Publish(new EventTwo { Content = $"{nameof(EventTwo)} sample content", PublishedOnUtc = DateTime.UtcNow @@ -39,4 +46,4 @@ await endpointInstance.Publish(new EventTwo Console.WriteLine("Press any key to exit"); Console.ReadKey(); -await endpointInstance.Stop(); \ No newline at end of file +await host.StopAsync(); \ No newline at end of file diff --git a/samples/azure-service-bus-netstandard/native-integration-pub-sub/ASBS_6/Publisher/Publisher.csproj b/samples/azure-service-bus-netstandard/native-integration-pub-sub/ASBS_6/Publisher/Publisher.csproj index 7cf049b7fea..e8075b34295 100644 --- a/samples/azure-service-bus-netstandard/native-integration-pub-sub/ASBS_6/Publisher/Publisher.csproj +++ b/samples/azure-service-bus-netstandard/native-integration-pub-sub/ASBS_6/Publisher/Publisher.csproj @@ -11,6 +11,6 @@ - + diff --git a/samples/bridge/azure-service-bus-msmq-bridge/Bridge_5/AsbEndpoint/AsbEndpoint.csproj b/samples/bridge/azure-service-bus-msmq-bridge/Bridge_5/AsbEndpoint/AsbEndpoint.csproj index a9ce6c979b4..77631328ccc 100644 --- a/samples/bridge/azure-service-bus-msmq-bridge/Bridge_5/AsbEndpoint/AsbEndpoint.csproj +++ b/samples/bridge/azure-service-bus-msmq-bridge/Bridge_5/AsbEndpoint/AsbEndpoint.csproj @@ -5,8 +5,7 @@ 14.0 - - + diff --git a/samples/bridge/azure-service-bus-msmq-bridge/Bridge_5/AsbEndpoint/Program.cs b/samples/bridge/azure-service-bus-msmq-bridge/Bridge_5/AsbEndpoint/Program.cs index 61a9bc5e6f0..4b143ededa5 100644 --- a/samples/bridge/azure-service-bus-msmq-bridge/Bridge_5/AsbEndpoint/Program.cs +++ b/samples/bridge/azure-service-bus-msmq-bridge/Bridge_5/AsbEndpoint/Program.cs @@ -27,7 +27,7 @@ var builder = Host.CreateApplicationBuilder(args); //builder.Logging.SetMinimumLevel(LogLevel.Debug); -builder.UseNServiceBus(endpointConfiguration); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); var sendOptions = new SendOptions(); sendOptions.SetDestination("Samples.MessagingBridge.MsmqEndpoint"); @@ -60,4 +60,4 @@ } } -await host.StopAsync(); +await host.StopAsync(); diff --git a/samples/bridge/azure-service-bus-msmq-bridge/Bridge_5/Bridge/Bridge.csproj b/samples/bridge/azure-service-bus-msmq-bridge/Bridge_5/Bridge/Bridge.csproj index fbab7663252..5fbd2568f23 100644 --- a/samples/bridge/azure-service-bus-msmq-bridge/Bridge_5/Bridge/Bridge.csproj +++ b/samples/bridge/azure-service-bus-msmq-bridge/Bridge_5/Bridge/Bridge.csproj @@ -5,8 +5,7 @@ 14.0 - - + diff --git a/samples/callbacks/Callbacks_6/Receiver/Program.cs b/samples/callbacks/Callbacks_6/Receiver/Program.cs index 19388c2c003..aaaa3a91984 100644 --- a/samples/callbacks/Callbacks_6/Receiver/Program.cs +++ b/samples/callbacks/Callbacks_6/Receiver/Program.cs @@ -7,23 +7,16 @@ class Program { public static async Task Main(string[] args) { - await CreateHostBuilder(args).Build().RunAsync(); - } - - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureServices((hostContext, services) => - { - Console.Title = "Receiver"; - }).UseNServiceBus(x => - { - var endpointConfiguration = new EndpointConfiguration("Samples.Callbacks.Receiver"); - endpointConfiguration.UsePersistence(); - endpointConfiguration.UseSerialization(); - endpointConfiguration.UseTransport(new LearningTransport()); - endpointConfiguration.EnableCallbacks(makesRequests: false); + Console.Title = "Receiver"; - return endpointConfiguration; - }); + var endpointConfiguration = new EndpointConfiguration("Samples.Callbacks.Receiver"); + endpointConfiguration.UsePersistence(); + endpointConfiguration.UseSerialization(); + endpointConfiguration.UseTransport(new LearningTransport()); + endpointConfiguration.EnableCallbacks(makesRequests: false); + var builder = Host.CreateApplicationBuilder(args); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + await builder.Build().RunAsync(); + } } diff --git a/samples/callbacks/Callbacks_6/Receiver/Receiver.csproj b/samples/callbacks/Callbacks_6/Receiver/Receiver.csproj index d0e9f3aaaa9..a2562992ba7 100644 --- a/samples/callbacks/Callbacks_6/Receiver/Receiver.csproj +++ b/samples/callbacks/Callbacks_6/Receiver/Receiver.csproj @@ -7,6 +7,5 @@ - \ No newline at end of file diff --git a/samples/callbacks/Callbacks_6/Sender/Program.cs b/samples/callbacks/Callbacks_6/Sender/Program.cs index 869078ec949..289b5e0bee6 100644 --- a/samples/callbacks/Callbacks_6/Sender/Program.cs +++ b/samples/callbacks/Callbacks_6/Sender/Program.cs @@ -1,5 +1,7 @@ using System; using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NServiceBus; class Program @@ -14,7 +16,12 @@ static async Task Main() endpointConfiguration.MakeInstanceUniquelyAddressable("1"); endpointConfiguration.EnableCallbacks(); - var endpointInstance = await Endpoint.Start(endpointConfiguration); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + var messageSession = host.Services.GetRequiredService(); + await host.StartAsync(); + Console.WriteLine("Press 'E' to send a message with an enum return"); Console.WriteLine("Press 'I' to send a message with an int return"); Console.WriteLine("Press 'O' to send a message with an object return"); @@ -27,26 +34,26 @@ static async Task Main() if (key.Key == ConsoleKey.E) { - await SendEnumMessage(endpointInstance); + await SendEnumMessage(messageSession); continue; } if (key.Key == ConsoleKey.I) { - await SendIntMessage(endpointInstance); + await SendIntMessage(messageSession); continue; } if (key.Key == ConsoleKey.O) { - await SendObjectMessage(endpointInstance); + await SendObjectMessage(messageSession); continue; } break; } - await endpointInstance.Stop(); + await host.StopAsync(); } - static async Task SendEnumMessage(IEndpointInstance endpointInstance) + static async Task SendEnumMessage(IMessageSession messageSession) { Console.WriteLine("Message sent"); @@ -55,13 +62,13 @@ static async Task SendEnumMessage(IEndpointInstance endpointInstance) var message = new EnumMessage(); var sendOptions = new SendOptions(); sendOptions.SetDestination("Samples.Callbacks.Receiver"); - var status = await endpointInstance.Request(message, sendOptions); + var status = await messageSession.Request(message, sendOptions); Console.WriteLine($"Callback received with status:{status}"); #endregion } - static async Task SendIntMessage(IEndpointInstance endpointInstance) + static async Task SendIntMessage(IMessageSession messageSession) { Console.WriteLine("Message sent"); @@ -70,13 +77,13 @@ static async Task SendIntMessage(IEndpointInstance endpointInstance) var message = new IntMessage(); var sendOptions = new SendOptions(); sendOptions.SetDestination("Samples.Callbacks.Receiver"); - var response = await endpointInstance.Request(message, sendOptions); + var response = await messageSession.Request(message, sendOptions); Console.WriteLine($"Callback received with response:{response}"); #endregion } - static async Task SendObjectMessage(IEndpointInstance endpointInstance) + static async Task SendObjectMessage(IMessageSession messageSession) { Console.WriteLine("Message sent"); @@ -85,7 +92,7 @@ static async Task SendObjectMessage(IEndpointInstance endpointInstance) var message = new ObjectMessage(); var sendOptions = new SendOptions(); sendOptions.SetDestination("Samples.Callbacks.Receiver"); - var response = await endpointInstance.Request(message, sendOptions); + var response = await messageSession.Request(message, sendOptions); Console.WriteLine($"Callback received with response property value:{response.Property}"); #endregion diff --git a/samples/callbacks/Callbacks_6/Shared/Shared.csproj b/samples/callbacks/Callbacks_6/Shared/Shared.csproj index a2f224dbcc9..c30a9c9d8aa 100644 --- a/samples/callbacks/Callbacks_6/Shared/Shared.csproj +++ b/samples/callbacks/Callbacks_6/Shared/Shared.csproj @@ -4,6 +4,6 @@ 14.0 - + \ No newline at end of file diff --git a/samples/callbacks/Callbacks_6/WebSender/Program.cs b/samples/callbacks/Callbacks_6/WebSender/Program.cs index 34316044f11..6e321954514 100644 --- a/samples/callbacks/Callbacks_6/WebSender/Program.cs +++ b/samples/callbacks/Callbacks_6/WebSender/Program.cs @@ -8,7 +8,7 @@ endpointConfiguration.MakeInstanceUniquelyAddressable("1"); endpointConfiguration.EnableCallbacks(); -builder.UseNServiceBus(endpointConfiguration); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); builder.Services.AddControllersWithViews(); diff --git a/samples/callbacks/Callbacks_6/WebSender/WebSender.csproj b/samples/callbacks/Callbacks_6/WebSender/WebSender.csproj index 8192025a87a..8316c8eda97 100644 --- a/samples/callbacks/Callbacks_6/WebSender/WebSender.csproj +++ b/samples/callbacks/Callbacks_6/WebSender/WebSender.csproj @@ -12,7 +12,6 @@ - diff --git a/samples/consumer-driven-contracts/Core_10/Consumer1/Consumer1.csproj b/samples/consumer-driven-contracts/Core_10/Consumer1/Consumer1.csproj index 4a3a00cc6c4..984a3a0f8ae 100644 --- a/samples/consumer-driven-contracts/Core_10/Consumer1/Consumer1.csproj +++ b/samples/consumer-driven-contracts/Core_10/Consumer1/Consumer1.csproj @@ -7,8 +7,7 @@ - - + \ No newline at end of file diff --git a/samples/consumer-driven-contracts/Core_10/Consumer1/Program.cs b/samples/consumer-driven-contracts/Core_10/Consumer1/Program.cs index 2eb6557baeb..720e5635164 100644 --- a/samples/consumer-driven-contracts/Core_10/Consumer1/Program.cs +++ b/samples/consumer-driven-contracts/Core_10/Consumer1/Program.cs @@ -7,22 +7,16 @@ class Program { public static async Task Main(string[] args) { - await CreateHostBuilder(args).Build().RunAsync(); - } + Console.Title = "Consumer1"; - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureServices((hostContext, services) => - { - Console.Title = "Consumer1"; - }).UseNServiceBus(x => - { - var endpointConfiguration = new EndpointConfiguration("Samples.ConsumerDrivenContracts.Consumer1"); - var transport = endpointConfiguration.UseTransport(new LearningTransport()); - endpointConfiguration.UseSerialization(); + var endpointConfiguration = new EndpointConfiguration("Samples.ConsumerDrivenContracts.Consumer1"); + var transport = endpointConfiguration.UseTransport(new LearningTransport()); + endpointConfiguration.UseSerialization(); + endpointConfiguration.SendFailedMessagesTo("error"); + endpointConfiguration.EnableInstallers(); - endpointConfiguration.SendFailedMessagesTo("error"); - endpointConfiguration.EnableInstallers(); - return endpointConfiguration; - }); + var builder = Host.CreateApplicationBuilder(args); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + await builder.Build().RunAsync(); + } } \ No newline at end of file diff --git a/samples/consumer-driven-contracts/Core_10/Consumer2/Consumer2.csproj b/samples/consumer-driven-contracts/Core_10/Consumer2/Consumer2.csproj index 4a3a00cc6c4..984a3a0f8ae 100644 --- a/samples/consumer-driven-contracts/Core_10/Consumer2/Consumer2.csproj +++ b/samples/consumer-driven-contracts/Core_10/Consumer2/Consumer2.csproj @@ -7,8 +7,7 @@ - - + \ No newline at end of file diff --git a/samples/consumer-driven-contracts/Core_10/Consumer2/Program.cs b/samples/consumer-driven-contracts/Core_10/Consumer2/Program.cs index 102dc7fc171..37f83802ef2 100644 --- a/samples/consumer-driven-contracts/Core_10/Consumer2/Program.cs +++ b/samples/consumer-driven-contracts/Core_10/Consumer2/Program.cs @@ -7,23 +7,16 @@ class Program { public static async Task Main(string[] args) { - await CreateHostBuilder(args).Build().RunAsync(); - } - - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureServices((hostContext, services) => - { - Console.Title = "Consumer2"; - }).UseNServiceBus(x => - { - var endpointConfiguration = new EndpointConfiguration("Samples.ConsumerDrivenContracts.Consumer2"); - var transport = endpointConfiguration.UseTransport(new LearningTransport()); - endpointConfiguration.UseSerialization(); + Console.Title = "Consumer2"; - endpointConfiguration.SendFailedMessagesTo("error"); - endpointConfiguration.EnableInstallers(); - return endpointConfiguration; - }); + var endpointConfiguration = new EndpointConfiguration("Samples.ConsumerDrivenContracts.Consumer2"); + var transport = endpointConfiguration.UseTransport(new LearningTransport()); + endpointConfiguration.UseSerialization(); + endpointConfiguration.SendFailedMessagesTo("error"); + endpointConfiguration.EnableInstallers(); + var builder = Host.CreateApplicationBuilder(args); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + await builder.Build().RunAsync(); + } } \ No newline at end of file diff --git a/samples/consumer-driven-contracts/Core_10/Dockerfile b/samples/consumer-driven-contracts/Core_10/Dockerfile deleted file mode 100644 index eba32b97c64..00000000000 --- a/samples/consumer-driven-contracts/Core_10/Dockerfile +++ /dev/null @@ -1,35 +0,0 @@ -# Build from repository root with: -# podman build -f samples/consumer-driven-contracts/Core_10/Dockerfile -t sample-core10 . -# docker build -f samples/consumer-driven-contracts/Core_10/Dockerfile -t sample-core10 . -FROM mcr.microsoft.com/dotnet/sdk:10.0-preview - -# Install expect for automated input -RUN apt-get update && apt-get install -y expect procps && rm -rf /var/lib/apt/lists/* - -# Set working directory -WORKDIR /app - -# Copy configuration files from repository root -COPY nuget.config ./ -COPY Directory.Build.props ./ -COPY BannedSymbols.txt ./ - -# Copy solution and project files -COPY samples/consumer-driven-contracts/Core_10/*.sln ./ -COPY samples/consumer-driven-contracts/Core_10/Consumer1/*.csproj Consumer1/ -COPY samples/consumer-driven-contracts/Core_10/Consumer2/*.csproj Consumer2/ -COPY samples/consumer-driven-contracts/Core_10/Producer/*.csproj Producer/ - -# Restore packages -RUN dotnet restore - -# Copy all source code -COPY samples/consumer-driven-contracts/Core_10/ . - -# Restore again to ensure all packages are available after copying all files -RUN dotnet restore - -# Build the solution using the latest framework -RUN dotnet build --no-restore --framework net10.0 - -CMD ["/app/run_sample.sh"] diff --git a/samples/consumer-driven-contracts/Core_10/Producer/Producer.csproj b/samples/consumer-driven-contracts/Core_10/Producer/Producer.csproj index 38d9a6f7b0c..7de6e84dd57 100644 --- a/samples/consumer-driven-contracts/Core_10/Producer/Producer.csproj +++ b/samples/consumer-driven-contracts/Core_10/Producer/Producer.csproj @@ -7,7 +7,7 @@ - + diff --git a/samples/consumer-driven-contracts/Core_10/Producer/Program.cs b/samples/consumer-driven-contracts/Core_10/Producer/Program.cs index a5689a14ec2..17bed102be1 100644 --- a/samples/consumer-driven-contracts/Core_10/Producer/Program.cs +++ b/samples/consumer-driven-contracts/Core_10/Producer/Program.cs @@ -1,5 +1,7 @@ using System; using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NServiceBus; using Publisher.Contracts; @@ -8,6 +10,7 @@ class Program static async Task Main() { Console.Title = "Producer"; + var endpointConfiguration = new EndpointConfiguration("Samples.ConsumerDrivenContracts.Producer"); endpointConfiguration.UseTransport(new LearningTransport()); endpointConfiguration.UseSerialization(); @@ -15,12 +18,18 @@ static async Task Main() endpointConfiguration.SendFailedMessagesTo("error"); endpointConfiguration.EnableInstallers(); - var endpointInstance = await Endpoint.Start(endpointConfiguration); - await Start(endpointInstance); - await endpointInstance.Stop(); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + var messageSession = host.Services.GetRequiredService(); + await host.StartAsync(); + + await Start(messageSession); + + await host.StopAsync(); } - static async Task Start(IEndpointInstance endpointInstance) + static async Task Start(IMessageSession messageSession) { Console.WriteLine("Press 'p' to publish event"); Console.WriteLine("Press any other key to exit"); @@ -38,7 +47,7 @@ static async Task Start(IEndpointInstance endpointInstance) Consumer1Property = "Consumer1Info", Consumer2Property = "Consumer2Info" }; - await endpointInstance.Publish(myEvent); + await messageSession.Publish(myEvent); continue; } diff --git a/samples/consumer-driven-contracts/Core_10/run_sample.sh b/samples/consumer-driven-contracts/Core_10/run_sample.sh deleted file mode 100755 index 9cdb3bbda67..00000000000 --- a/samples/consumer-driven-contracts/Core_10/run_sample.sh +++ /dev/null @@ -1,121 +0,0 @@ -#!/bin/bash - -# Colors for output -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -NC='\033[0m' # No Color - -echo -e "${YELLOW}Starting Consumer-Driven Contracts Sample${NC}" - -# Create logs directory -mkdir -p /app/logs - -# Start Consumer1 in background -echo -e "${YELLOW}Starting Consumer1...${NC}" -dotnet run --project Consumer1 --framework net10.0 > /app/logs/consumer1.log 2>&1 & -CONSUMER1_PID=$! - -# Start Consumer2 in background -echo -e "${YELLOW}Starting Consumer2...${NC}" -dotnet run --project Consumer2 --framework net10.0 > /app/logs/consumer2.log 2>&1 & -CONSUMER2_PID=$!# Wait for consumers to initialize by checking log files -echo -e "${YELLOW}Waiting for consumers to initialize...${NC}" -timeout=30 -counter=0 - -while [ $counter -lt $timeout ]; do - if grep -q "Press Ctrl+C to shut down" /app/logs/consumer1.log 2>/dev/null && \ - grep -q "Press Ctrl+C to shut down" /app/logs/consumer2.log 2>/dev/null; then - break - fi - sleep 1 - counter=$((counter + 1)) -done - -if [ $counter -eq $timeout ]; then - echo -e "${RED}Timeout: Consumers failed to initialize within ${timeout} seconds${NC}" - echo -e "${YELLOW}Consumer1 log:${NC}" - cat /app/logs/consumer1.log 2>/dev/null || echo "No log found" - echo -e "${YELLOW}Consumer2 log:${NC}" - cat /app/logs/consumer2.log 2>/dev/null || echo "No log found" - exit 1 -fi - -echo -e "${GREEN}Consumers started successfully${NC}" - -# Create expect script for automated Producer interaction -cat > /app/producer_automation.exp << 'EXPECT_EOF' -#!/usr/bin/expect - -set timeout 30 -spawn dotnet run --project Producer --framework net10.0 - -# Wait for the prompt -expect "Press 'p' to publish event" - -# Send 'p' to publish -send "p\r" - -# Wait a moment for the message to be published -sleep 2 - -# Send any other key to exit -send "q\r" - -expect eof -EXPECT_EOF - -chmod +x /app/producer_automation.exp - -# Run the Producer with automated input -echo -e "${YELLOW}Starting Producer and publishing event...${NC}" -/app/producer_automation.exp > /app/logs/producer.log 2>&1 - -# Wait for message processing -echo -e "${YELLOW}Waiting for message processing...${NC}" -sleep 5 - -# Check logs for expected behavior -echo -e "${YELLOW}Verifying results...${NC}" - -CONSUMER1_SUCCESS=false -CONSUMER2_SUCCESS=false - -# Check Consumer1 log for Consumer1Info -if grep -q "Consumer1Info" /app/logs/consumer1.log; then - echo -e "${GREEN}✓ Consumer1 successfully received and processed Consumer1Contract${NC}" - CONSUMER1_SUCCESS=true -else - echo -e "${RED}✗ Consumer1 did not process Consumer1Contract${NC}" -fi - -# Check Consumer2 log for Consumer2Info -if grep -q "Consumer2Info" /app/logs/consumer2.log; then - echo -e "${GREEN}✓ Consumer2 successfully received and processed Consumer2Contract${NC}" - CONSUMER2_SUCCESS=true -else - echo -e "${RED}✗ Consumer2 did not process Consumer2Contract${NC}" -fi - -# Show log outputs -echo -e "\n${YELLOW}=== Consumer1 Log ===${NC}" -cat /app/logs/consumer1.log - -echo -e "\n${YELLOW}=== Consumer2 Log ===${NC}" -cat /app/logs/consumer2.log - -echo -e "\n${YELLOW}=== Producer Log ===${NC}" -cat /app/logs/producer.log - -# Cleanup processes -kill $CONSUMER1_PID $CONSUMER2_PID 2>/dev/null || true - -# Final result -if $CONSUMER1_SUCCESS && $CONSUMER2_SUCCESS; then - echo -e "\n${GREEN}🎉 Sample completed successfully! Both consumers received their respective contracts.${NC}" - exit 0 -else - echo -e "\n${RED}❌ Sample failed - not all consumers received their expected messages.${NC}" - exit 1 -fi diff --git a/samples/consumer-driven-contracts/Core_9/Dockerfile b/samples/consumer-driven-contracts/Core_9/Dockerfile deleted file mode 100644 index 6702117d5f1..00000000000 --- a/samples/consumer-driven-contracts/Core_9/Dockerfile +++ /dev/null @@ -1,35 +0,0 @@ -# Build from repository root with: -# podman build -f samples/consumer-driven-contracts/Core_9/Dockerfile -t sample-core9 . -# docker build -f samples/consumer-driven-contracts/Core_9/Dockerfile -t sample-core9 . -FROM mcr.microsoft.com/dotnet/sdk:9.0 - -# Install expect for automated input -RUN apt-get update && apt-get install -y expect procps && rm -rf /var/lib/apt/lists/* - -# Set working directory -WORKDIR /app - -# Copy configuration files from repository root -COPY nuget.config ./ -COPY Directory.Build.props ./ -COPY BannedSymbols.txt ./ - -# Copy solution and project files -COPY samples/consumer-driven-contracts/Core_9/*.sln ./ -COPY samples/consumer-driven-contracts/Core_9/Consumer1/*.csproj Consumer1/ -COPY samples/consumer-driven-contracts/Core_9/Consumer2/*.csproj Consumer2/ -COPY samples/consumer-driven-contracts/Core_9/Producer/*.csproj Producer/ - -# Restore packages -RUN dotnet restore - -# Copy all source code -COPY samples/consumer-driven-contracts/Core_9/ . - -# Restore again to ensure all packages are available after copying all files -RUN dotnet restore - -# Build the solution using the latest framework -RUN dotnet build --no-restore --framework net9.0 - -CMD ["/app/run_sample.sh"] diff --git a/samples/consumer-driven-contracts/Core_9/run_sample.sh b/samples/consumer-driven-contracts/Core_9/run_sample.sh deleted file mode 100755 index 136da1ea678..00000000000 --- a/samples/consumer-driven-contracts/Core_9/run_sample.sh +++ /dev/null @@ -1,123 +0,0 @@ -#!/bin/bash - -# Colors for output -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -NC='\033[0m' # No Color - -echo -e "${YELLOW}Starting Consumer-Driven Contracts Sample${NC}" - -# Create logs directory -mkdir -p /app/logs - -# Start Consumer1 in background -echo -e "${YELLOW}Starting Consumer1...${NC}" -dotnet run --project Consumer1 --framework net9.0 > /app/logs/consumer1.log 2>&1 & -CONSUMER1_PID=$! - -# Start Consumer2 in background -echo -e "${YELLOW}Starting Consumer2...${NC}" -dotnet run --project Consumer2 --framework net9.0 > /app/logs/consumer2.log 2>&1 & -CONSUMER2_PID=$! - -# Wait for consumers to initialize by checking log files -echo -e "${YELLOW}Waiting for consumers to initialize...${NC}" -timeout=30 -counter=0 - -while [ $counter -lt $timeout ]; do - if grep -q "Press Ctrl+C to shut down" /app/logs/consumer1.log 2>/dev/null && \ - grep -q "Press Ctrl+C to shut down" /app/logs/consumer2.log 2>/dev/null; then - break - fi - sleep 1 - counter=$((counter + 1)) -done - -if [ $counter -eq $timeout ]; then - echo -e "${RED}Timeout: Consumers failed to initialize within ${timeout} seconds${NC}" - echo -e "${YELLOW}Consumer1 log:${NC}" - cat /app/logs/consumer1.log 2>/dev/null || echo "No log found" - echo -e "${YELLOW}Consumer2 log:${NC}" - cat /app/logs/consumer2.log 2>/dev/null || echo "No log found" - exit 1 -fi - -echo -e "${GREEN}Consumers started successfully${NC}" - -# Create expect script for automated Producer interaction -cat > /app/producer_automation.exp << 'EXPECT_EOF' -#!/usr/bin/expect - -set timeout 30 -spawn dotnet run --project Producer --framework net9.0 - -# Wait for the prompt -expect "Press 'p' to publish event" - -# Send 'p' to publish -send "p\r" - -# Wait a moment for the message to be published -sleep 2 - -# Send any other key to exit -send "q\r" - -expect eof -EXPECT_EOF - -chmod +x /app/producer_automation.exp - -# Run the Producer with automated input -echo -e "${YELLOW}Starting Producer and publishing event...${NC}" -/app/producer_automation.exp > /app/logs/producer.log 2>&1 - -# Wait for message processing -echo -e "${YELLOW}Waiting for message processing...${NC}" -sleep 5 - -# Check logs for expected behavior -echo -e "${YELLOW}Verifying results...${NC}" - -CONSUMER1_SUCCESS=false -CONSUMER2_SUCCESS=false - -# Check Consumer1 log for Consumer1Info -if grep -q "Consumer1Info" /app/logs/consumer1.log; then - echo -e "${GREEN}✓ Consumer1 successfully received and processed Consumer1Contract${NC}" - CONSUMER1_SUCCESS=true -else - echo -e "${RED}✗ Consumer1 did not process Consumer1Contract${NC}" -fi - -# Check Consumer2 log for Consumer2Info -if grep -q "Consumer2Info" /app/logs/consumer2.log; then - echo -e "${GREEN}✓ Consumer2 successfully received and processed Consumer2Contract${NC}" - CONSUMER2_SUCCESS=true -else - echo -e "${RED}✗ Consumer2 did not process Consumer2Contract${NC}" -fi - -# Show log outputs -echo -e "\n${YELLOW}=== Consumer1 Log ===${NC}" -cat /app/logs/consumer1.log - -echo -e "\n${YELLOW}=== Consumer2 Log ===${NC}" -cat /app/logs/consumer2.log - -echo -e "\n${YELLOW}=== Producer Log ===${NC}" -cat /app/logs/producer.log - -# Cleanup processes -kill $CONSUMER1_PID $CONSUMER2_PID 2>/dev/null || true - -# Final result -if $CONSUMER1_SUCCESS && $CONSUMER2_SUCCESS; then - echo -e "\n${GREEN}🎉 Sample completed successfully! Both consumers received their respective contracts.${NC}" - exit 0 -else - echo -e "\n${RED}❌ Sample failed - not all consumers received their expected messages.${NC}" - exit 1 -fi diff --git a/samples/custom-recoverability/Core_10/Client/Program.cs b/samples/custom-recoverability/Core_10/Client/Program.cs index 0a018767f86..1651154f275 100644 --- a/samples/custom-recoverability/Core_10/Client/Program.cs +++ b/samples/custom-recoverability/Core_10/Client/Program.cs @@ -1,5 +1,7 @@ using System; using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NServiceBus; class Program @@ -12,7 +14,12 @@ static async Task Main() endpointConfiguration.UseTransport(new LearningTransport()); endpointConfiguration.UseSerialization(); - var endpointInstance = await Endpoint.Start(endpointConfiguration); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + var messageSession = host.Services.GetRequiredService(); + await host.StartAsync(); + Console.WriteLine("Press enter to send a message"); Console.WriteLine("Press any key to exit"); @@ -28,10 +35,10 @@ static async Task Main() { Id = id }; - await endpointInstance.Send("Samples.CustomRecoverability.Server", myMessage); + await messageSession.Send("Samples.CustomRecoverability.Server", myMessage); Console.WriteLine($"Sent a message with id: {id:N}"); } - await endpointInstance.Stop(); + await host.StopAsync(); } } diff --git a/samples/custom-recoverability/Core_10/Server/Program.cs b/samples/custom-recoverability/Core_10/Server/Program.cs index 6bf9f585bcf..1a4de271ae9 100644 --- a/samples/custom-recoverability/Core_10/Server/Program.cs +++ b/samples/custom-recoverability/Core_10/Server/Program.cs @@ -10,50 +10,41 @@ class Program public static async Task Main(string[] args) { - await CreateHostBuilder(args).Build().RunAsync(); - } - - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureServices((hostContext, services) => + var endpointConfiguration = new EndpointConfiguration("Samples.CustomRecoverability.Server"); + endpointConfiguration.UsePersistence(); + endpointConfiguration.UseTransport(new LearningTransport()); + endpointConfiguration.UseSerialization(); + var recoverability = endpointConfiguration.Recoverability(); + + #region disable + //recoverability.Delayed(settings => + //{ + // settings.NumberOfRetries(0); + //}); + #endregion + + #region addcustompolicy + recoverability.CustomPolicy(MyCustomRetryPolicy()); + #endregion + + #region addcustomheaders + recoverability.Failed( + failed => { - Console.Title = "Server"; - }).UseNServiceBus(x => - { - var endpointConfiguration = new EndpointConfiguration("Samples.CustomRecoverability.Server"); - endpointConfiguration.UsePersistence(); - endpointConfiguration.UseTransport(new LearningTransport()); - endpointConfiguration.UseSerialization(); - var recoverability = endpointConfiguration.Recoverability(); - - #region disable - //recoverability.Delayed(settings => - //{ - // settings.NumberOfRetries(0); - //}); - #endregion - - #region addcustompolicy - recoverability.CustomPolicy(MyCustomRetryPolicy()); - #endregion - - #region addcustomheaders - recoverability.Failed( - failed => + failed.HeaderCustomization(headers => { - failed.HeaderCustomization(headers => + if (headers.ContainsKey("NServiceBus.ExceptionInfo.Message")) { - if (headers.ContainsKey("NServiceBus.ExceptionInfo.Message")) - { - headers["NServiceBus.ExceptionInfo.Message"] = "message override"; - } - }); + headers["NServiceBus.ExceptionInfo.Message"] = "message override"; + } }); - #endregion - - return endpointConfiguration; }); + #endregion + var builder = Host.CreateApplicationBuilder(args); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + await builder.Build().RunAsync(); + } #region mycustomretrypolicy private static Func MyCustomRetryPolicy() diff --git a/samples/custom-recoverability/Core_10/Server/Server.csproj b/samples/custom-recoverability/Core_10/Server/Server.csproj index 1c9aa5a1f80..50585add435 100644 --- a/samples/custom-recoverability/Core_10/Server/Server.csproj +++ b/samples/custom-recoverability/Core_10/Server/Server.csproj @@ -10,8 +10,4 @@ - - - - \ No newline at end of file diff --git a/samples/custom-recoverability/Core_10/Shared/Shared.csproj b/samples/custom-recoverability/Core_10/Shared/Shared.csproj index afb41271b56..5bf55bdca71 100644 --- a/samples/custom-recoverability/Core_10/Shared/Shared.csproj +++ b/samples/custom-recoverability/Core_10/Shared/Shared.csproj @@ -6,7 +6,7 @@ - + \ No newline at end of file diff --git a/samples/dependency-injection/externally-managed-mode/Core_10/ExternallyManagedContainer.sln b/samples/dependency-injection/externally-managed-mode/Core_10/ExternallyManagedContainer.sln deleted file mode 100644 index 72ea35258fc..00000000000 --- a/samples/dependency-injection/externally-managed-mode/Core_10/ExternallyManagedContainer.sln +++ /dev/null @@ -1,21 +0,0 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29728.190 -MinimumVisualStudioVersion = 15.0.26730.12 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Sample", "Sample\Sample.csproj", "{6E6C9C2A-8D9B-41AF-B5E5-1AF5310686E7}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {6E6C9C2A-8D9B-41AF-B5E5-1AF5310686E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6E6C9C2A-8D9B-41AF-B5E5-1AF5310686E7}.Debug|Any CPU.Build.0 = Debug|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {3673C976-8AFC-4169-A103-E016521D0868} - EndGlobalSection -EndGlobal diff --git a/samples/dependency-injection/externally-managed-mode/Core_10/Sample/Greeter.cs b/samples/dependency-injection/externally-managed-mode/Core_10/Sample/Greeter.cs deleted file mode 100644 index 105f9492b9e..00000000000 --- a/samples/dependency-injection/externally-managed-mode/Core_10/Sample/Greeter.cs +++ /dev/null @@ -1,11 +0,0 @@ -using NServiceBus.Logging; - -public class Greeter -{ - static readonly ILog log = LogManager.GetLogger(); - - public void SayHello() - { - log.Info("Hello from Greeter."); - } -} \ No newline at end of file diff --git a/samples/dependency-injection/externally-managed-mode/Core_10/Sample/MessageSender.cs b/samples/dependency-injection/externally-managed-mode/Core_10/Sample/MessageSender.cs deleted file mode 100644 index 4c0d33ca78a..00000000000 --- a/samples/dependency-injection/externally-managed-mode/Core_10/Sample/MessageSender.cs +++ /dev/null @@ -1,10 +0,0 @@ -#region InjectingMessageSession -public class MessageSender(IMessageSession messageSession) -{ - public Task SendMessage() - { - var myMessage = new MyMessage(); - return messageSession.SendLocal(myMessage); - } -} -#endregion \ No newline at end of file diff --git a/samples/dependency-injection/externally-managed-mode/Core_10/Sample/MyHandler.cs b/samples/dependency-injection/externally-managed-mode/Core_10/Sample/MyHandler.cs deleted file mode 100644 index a506df30dc1..00000000000 --- a/samples/dependency-injection/externally-managed-mode/Core_10/Sample/MyHandler.cs +++ /dev/null @@ -1,10 +0,0 @@ -#region InjectingDependency -public class MyHandler(Greeter greeter) : IHandleMessages -{ - public Task Handle(MyMessage message, IMessageHandlerContext context) - { - greeter.SayHello(); - return Task.CompletedTask; - } -} -#endregion diff --git a/samples/dependency-injection/externally-managed-mode/Core_10/Sample/MyMessage.cs b/samples/dependency-injection/externally-managed-mode/Core_10/Sample/MyMessage.cs deleted file mode 100644 index 50cb56a5b56..00000000000 --- a/samples/dependency-injection/externally-managed-mode/Core_10/Sample/MyMessage.cs +++ /dev/null @@ -1 +0,0 @@ -public record MyMessage : IMessage; \ No newline at end of file diff --git a/samples/dependency-injection/externally-managed-mode/Core_10/Sample/Program.cs b/samples/dependency-injection/externally-managed-mode/Core_10/Sample/Program.cs deleted file mode 100644 index da53032fb15..00000000000 --- a/samples/dependency-injection/externally-managed-mode/Core_10/Sample/Program.cs +++ /dev/null @@ -1,38 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; - -Console.Title = "ExternallyManagedContainer"; - -var endpointConfiguration = new EndpointConfiguration("Sample"); -endpointConfiguration.UseSerialization(); -endpointConfiguration.UseTransport(new LearningTransport()); - -#region ContainerConfiguration - -// ServiceCollection is provided by Microsoft.Extensions.DependencyInjection -var serviceCollection = new ServiceCollection(); - -// most dependencies may now be registered -serviceCollection.AddSingleton(); -serviceCollection.AddSingleton(); - -// EndpointWithExternallyManagedContainer.Create accepts an IServiceCollection, -// which is inherited by ServiceCollection -var endpointWithExternallyManagedContainer = EndpointWithExternallyManagedContainer - .Create(endpointConfiguration, serviceCollection); - -// if IMessageSession is required as dependency, it may now be registered -serviceCollection.AddSingleton(p => endpointWithExternallyManagedContainer.MessageSession.Value); - -#endregion - -using var serviceProvider = serviceCollection.BuildServiceProvider(); - -var endpoint = await endpointWithExternallyManagedContainer.Start(serviceProvider); - -var sender = serviceProvider.GetRequiredService(); -await sender.SendMessage(); - -Console.WriteLine("Press any key to exit"); -Console.ReadKey(); - -await endpoint.Stop(); diff --git a/samples/dependency-injection/externally-managed-mode/Core_10/Sample/Sample.csproj b/samples/dependency-injection/externally-managed-mode/Core_10/Sample/Sample.csproj deleted file mode 100644 index edab691f434..00000000000 --- a/samples/dependency-injection/externally-managed-mode/Core_10/Sample/Sample.csproj +++ /dev/null @@ -1,14 +0,0 @@ - - - - net10.0 - Exe - enable - 14.0 - - - - - - - \ No newline at end of file diff --git a/samples/dependency-injection/externally-managed-mode/sample.md b/samples/dependency-injection/externally-managed-mode/sample.md index 536c8a7982a..a40b909407c 100644 --- a/samples/dependency-injection/externally-managed-mode/sample.md +++ b/samples/dependency-injection/externally-managed-mode/sample.md @@ -2,11 +2,15 @@ title: Externally Managed Mode summary: A sample that uses the externally managed mode feature to configure a dependency injection container. component: Core +versions: '[,10)' reviewed: 2025-10-03 related: - nservicebus/dependency-injection --- +> [!WARNING] +> In NServiceBus version 10.2.0 and above, externally managed mode is no longer a relevant concept, as integration with the Microsoft .NET Host is integrated directly into NServiceBus. + ### Configuring the endpoint This sample configures an endpoint to use [externally managed mode](/nservicebus/dependency-injection/#modes-of-operation-externally-managed-mode) with [Microsoft's dependency injection container](https://www.nuget.org/packages/Microsoft.Extensions.DependencyInjection) and registers some dependencies. diff --git a/samples/encryption/basic-encryption/PropertyEncryption_6/Endpoint1/Program.cs b/samples/encryption/basic-encryption/PropertyEncryption_6/Endpoint1/Program.cs index 7d4226debbb..c94f6984bfd 100644 --- a/samples/encryption/basic-encryption/PropertyEncryption_6/Endpoint1/Program.cs +++ b/samples/encryption/basic-encryption/PropertyEncryption_6/Endpoint1/Program.cs @@ -1,5 +1,7 @@ using System; using System.Collections.Generic; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NServiceBus; Console.Title = "Endpoint1"; @@ -10,7 +12,14 @@ endpointConfiguration.UsePersistence(); endpointConfiguration.UseTransport(new LearningTransport()); endpointConfiguration.UseSerialization(); -var endpointInstance = await Endpoint.Start(endpointConfiguration); + +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +var host = builder.Build(); +var messageSession = host.Services.GetRequiredService(); +await host.StartAsync(); + + var message = new MessageWithSecretData { Secret = "betcha can't guess my secret", @@ -32,8 +41,8 @@ } } }; -await endpointInstance.Send("Samples.Encryption.Endpoint2", message); +await messageSession.Send("Samples.Encryption.Endpoint2", message); Console.WriteLine("MessageWithSecretData sent. Press any key to exit"); Console.ReadKey(); -await endpointInstance.Stop(); \ No newline at end of file +await host.StopAsync(); \ No newline at end of file diff --git a/samples/encryption/basic-encryption/PropertyEncryption_6/Endpoint2/Endpoint2.csproj b/samples/encryption/basic-encryption/PropertyEncryption_6/Endpoint2/Endpoint2.csproj index 9e08818dd1e..b47eec00209 100644 --- a/samples/encryption/basic-encryption/PropertyEncryption_6/Endpoint2/Endpoint2.csproj +++ b/samples/encryption/basic-encryption/PropertyEncryption_6/Endpoint2/Endpoint2.csproj @@ -4,9 +4,6 @@ Exe 14.0 - - - diff --git a/samples/encryption/basic-encryption/PropertyEncryption_6/Endpoint2/Program.cs b/samples/encryption/basic-encryption/PropertyEncryption_6/Endpoint2/Program.cs index 0d3cc6ba50e..ba3ecb1f68a 100644 --- a/samples/encryption/basic-encryption/PropertyEncryption_6/Endpoint2/Program.cs +++ b/samples/encryption/basic-encryption/PropertyEncryption_6/Endpoint2/Program.cs @@ -11,6 +11,6 @@ endpointConfiguration.UseTransport(new LearningTransport()); endpointConfiguration.UseSerialization(); -builder.UseNServiceBus(endpointConfiguration); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); await builder.Build().RunAsync(); \ No newline at end of file diff --git a/samples/encryption/basic-encryption/PropertyEncryption_6/Shared/Shared.csproj b/samples/encryption/basic-encryption/PropertyEncryption_6/Shared/Shared.csproj index e9acf03bfc5..80a8aa1f556 100644 --- a/samples/encryption/basic-encryption/PropertyEncryption_6/Shared/Shared.csproj +++ b/samples/encryption/basic-encryption/PropertyEncryption_6/Shared/Shared.csproj @@ -4,7 +4,7 @@ 14.0 - + \ No newline at end of file diff --git a/samples/encryption/encryption-conventions/PropertyEncryption_6/Endpoint1/Program.cs b/samples/encryption/encryption-conventions/PropertyEncryption_6/Endpoint1/Program.cs index e332ec5bb17..e0910e78807 100644 --- a/samples/encryption/encryption-conventions/PropertyEncryption_6/Endpoint1/Program.cs +++ b/samples/encryption/encryption-conventions/PropertyEncryption_6/Endpoint1/Program.cs @@ -1,5 +1,7 @@ using System; using System.Collections.Generic; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NServiceBus; Console.Title = "Endpoint1"; @@ -11,7 +13,13 @@ endpointConfiguration.UsePersistence(); endpointConfiguration.UseTransport(new LearningTransport()); endpointConfiguration.UseSerialization(); -var endpointInstance = await Endpoint.Start(endpointConfiguration); + +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +var host = builder.Build(); +var messageSession = host.Services.GetRequiredService(); +await host.StartAsync(); + var message = new MessageWithSecretData { EncryptedSecret = "betcha can't guess my secret", @@ -33,8 +41,8 @@ } } }; -await endpointInstance.Send("Samples.Encryption.Endpoint2", message); +await messageSession.Send("Samples.Encryption.Endpoint2", message); Console.WriteLine("MessageWithSecretData sent. Press any key to exit"); Console.ReadKey(); -await endpointInstance.Stop(); \ No newline at end of file +await host.StopAsync(); \ No newline at end of file diff --git a/samples/encryption/encryption-conventions/PropertyEncryption_6/Endpoint2/Endpoint2.csproj b/samples/encryption/encryption-conventions/PropertyEncryption_6/Endpoint2/Endpoint2.csproj index 9e08818dd1e..b47eec00209 100644 --- a/samples/encryption/encryption-conventions/PropertyEncryption_6/Endpoint2/Endpoint2.csproj +++ b/samples/encryption/encryption-conventions/PropertyEncryption_6/Endpoint2/Endpoint2.csproj @@ -4,9 +4,6 @@ Exe 14.0 - - - diff --git a/samples/encryption/encryption-conventions/PropertyEncryption_6/Endpoint2/Program.cs b/samples/encryption/encryption-conventions/PropertyEncryption_6/Endpoint2/Program.cs index 3caf4d3ac5c..221c666be74 100644 --- a/samples/encryption/encryption-conventions/PropertyEncryption_6/Endpoint2/Program.cs +++ b/samples/encryption/encryption-conventions/PropertyEncryption_6/Endpoint2/Program.cs @@ -13,5 +13,5 @@ endpointConfiguration.UseTransport(new LearningTransport()); endpointConfiguration.UseSerialization(); -builder.UseNServiceBus(endpointConfiguration); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); await builder.Build().RunAsync(); \ No newline at end of file diff --git a/samples/encryption/encryption-conventions/PropertyEncryption_6/Shared/Shared.csproj b/samples/encryption/encryption-conventions/PropertyEncryption_6/Shared/Shared.csproj index e9acf03bfc5..80a8aa1f556 100644 --- a/samples/encryption/encryption-conventions/PropertyEncryption_6/Shared/Shared.csproj +++ b/samples/encryption/encryption-conventions/PropertyEncryption_6/Shared/Shared.csproj @@ -4,7 +4,7 @@ 14.0 - + \ No newline at end of file diff --git a/samples/encryption/message-body-encryption/Core_10/Endpoint1/Program.cs b/samples/encryption/message-body-encryption/Core_10/Endpoint1/Program.cs index 660cd50436b..f6fde9db8a2 100644 --- a/samples/encryption/message-body-encryption/Core_10/Endpoint1/Program.cs +++ b/samples/encryption/message-body-encryption/Core_10/Endpoint1/Program.cs @@ -1,5 +1,7 @@ using System; using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NServiceBus; class Program @@ -17,15 +19,20 @@ static async Task Main() #endregion - var endpointInstance = await Endpoint.Start(endpointConfiguration); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + var messageSession = host.Services.GetRequiredService(); + await host.StartAsync(); + var completeOrder = new CompleteOrder { CreditCard = "123-456-789" }; - await endpointInstance.Send("Samples.MessageBodyEncryption.Endpoint2", completeOrder); + await messageSession.Send("Samples.MessageBodyEncryption.Endpoint2", completeOrder); Console.WriteLine("Message sent"); Console.WriteLine("Press any key to exit"); Console.ReadKey(); - await endpointInstance.Stop(); + await host.StopAsync(); } } diff --git a/samples/encryption/message-body-encryption/Core_10/Endpoint2/Endpoint2.csproj b/samples/encryption/message-body-encryption/Core_10/Endpoint2/Endpoint2.csproj index 9e08818dd1e..b47eec00209 100644 --- a/samples/encryption/message-body-encryption/Core_10/Endpoint2/Endpoint2.csproj +++ b/samples/encryption/message-body-encryption/Core_10/Endpoint2/Endpoint2.csproj @@ -4,9 +4,6 @@ Exe 14.0 - - - diff --git a/samples/encryption/message-body-encryption/Core_10/Endpoint2/Program.cs b/samples/encryption/message-body-encryption/Core_10/Endpoint2/Program.cs index b85083be70c..4d4422aa51e 100644 --- a/samples/encryption/message-body-encryption/Core_10/Endpoint2/Program.cs +++ b/samples/encryption/message-body-encryption/Core_10/Endpoint2/Program.cs @@ -11,5 +11,5 @@ endpointConfiguration.UseTransport(new LearningTransport()); endpointConfiguration.RegisterMessageEncryptor(); -builder.UseNServiceBus(endpointConfiguration); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); await builder.Build().RunAsync(); diff --git a/samples/encryption/message-body-encryption/Core_10/Shared/Shared.csproj b/samples/encryption/message-body-encryption/Core_10/Shared/Shared.csproj index a2f224dbcc9..c30a9c9d8aa 100644 --- a/samples/encryption/message-body-encryption/Core_10/Shared/Shared.csproj +++ b/samples/encryption/message-body-encryption/Core_10/Shared/Shared.csproj @@ -4,6 +4,6 @@ 14.0 - + \ No newline at end of file diff --git a/samples/entity-framework-core/SqlPersistence_9/Endpoint.SqlPersistence/Endpoint.SqlPersistence.csproj b/samples/entity-framework-core/SqlPersistence_9/Endpoint.SqlPersistence/Endpoint.SqlPersistence.csproj index 109ef2b7102..5df7dac868d 100644 --- a/samples/entity-framework-core/SqlPersistence_9/Endpoint.SqlPersistence/Endpoint.SqlPersistence.csproj +++ b/samples/entity-framework-core/SqlPersistence_9/Endpoint.SqlPersistence/Endpoint.SqlPersistence.csproj @@ -9,8 +9,7 @@ - - + diff --git a/samples/entity-framework-core/SqlPersistence_9/Endpoint.SqlPersistence/Program.cs b/samples/entity-framework-core/SqlPersistence_9/Endpoint.SqlPersistence/Program.cs index 767f8176daf..9014694eaa6 100644 --- a/samples/entity-framework-core/SqlPersistence_9/Endpoint.SqlPersistence/Program.cs +++ b/samples/entity-framework-core/SqlPersistence_9/Endpoint.SqlPersistence/Program.cs @@ -43,29 +43,26 @@ #region UnitOfWork_SQL -endpointConfiguration.RegisterComponents(c => +builder.Services.AddScoped(provider => { - c.AddScoped(b => - { - var session = b.GetRequiredService(); + var session = provider.GetRequiredService(); - var context = new ReceiverDataContext(new DbContextOptionsBuilder() - .UseSqlServer(session.Connection) - .Options); + var context = new ReceiverDataContext(new DbContextOptionsBuilder() + .UseSqlServer(session.Connection) + .Options); - //Use the same underlying ADO.NET transaction - context.Database.UseTransaction(session.Transaction); + //Use the same underlying ADO.NET transaction + context.Database.UseTransaction(session.Transaction); - //Ensure context is flushed before the transaction is committed - session.OnSaveChanges((s, token) => context.SaveChangesAsync(token)); + //Ensure context is flushed before the transaction is committed + session.OnSaveChanges((s, token) => context.SaveChangesAsync(token)); - return context; - }); + return context; }); #endregion -builder.UseNServiceBus(endpointConfiguration); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); var host = builder.Build(); await host.StartAsync(); diff --git a/samples/errorhandling/Core_10/Shared/Shared.csproj b/samples/errorhandling/Core_10/Shared/Shared.csproj index 11e2ac7f852..e367cf72d45 100644 --- a/samples/errorhandling/Core_10/Shared/Shared.csproj +++ b/samples/errorhandling/Core_10/Shared/Shared.csproj @@ -6,7 +6,7 @@ - + diff --git a/samples/errorhandling/Core_10/WithDelayedRetries/Program.cs b/samples/errorhandling/Core_10/WithDelayedRetries/Program.cs index a93c41441ac..8b93818ed7f 100644 --- a/samples/errorhandling/Core_10/WithDelayedRetries/Program.cs +++ b/samples/errorhandling/Core_10/WithDelayedRetries/Program.cs @@ -1,5 +1,7 @@ using System; using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NServiceBus; Console.Title = "WithDelayedRetries"; @@ -9,7 +11,11 @@ endpointConfiguration.UseSerialization(); endpointConfiguration.UseTransport(new LearningTransport()); -var endpointInstance = await Endpoint.Start(endpointConfiguration); +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +var host = builder.Build(); +var messageSession = host.Services.GetRequiredService(); +await host.StartAsync(); Console.WriteLine("Press enter to send a message that will throw an exception."); Console.WriteLine("Press any key to exit"); @@ -27,7 +33,7 @@ Id = Guid.NewGuid() }; - await endpointInstance.SendLocal(myMessage); + await messageSession.SendLocal(myMessage); } -await endpointInstance.Stop(); +await host.StopAsync(); diff --git a/samples/errorhandling/Core_10/WithDelayedRetries/WithDelayedRetries.csproj b/samples/errorhandling/Core_10/WithDelayedRetries/WithDelayedRetries.csproj index 48c359675f1..59a21997b7d 100644 --- a/samples/errorhandling/Core_10/WithDelayedRetries/WithDelayedRetries.csproj +++ b/samples/errorhandling/Core_10/WithDelayedRetries/WithDelayedRetries.csproj @@ -7,7 +7,7 @@ - + diff --git a/samples/errorhandling/Core_10/WithoutDelayedRetries/Program.cs b/samples/errorhandling/Core_10/WithoutDelayedRetries/Program.cs index dc05f373298..ea9afa7742e 100644 --- a/samples/errorhandling/Core_10/WithoutDelayedRetries/Program.cs +++ b/samples/errorhandling/Core_10/WithoutDelayedRetries/Program.cs @@ -1,5 +1,7 @@ using System; using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NServiceBus; Console.Title = "WithoutDelayedRetries"; @@ -18,7 +20,11 @@ endpointConfiguration.UseSerialization(); endpointConfiguration.UseTransport(new LearningTransport()); -var endpointInstance = await Endpoint.Start(endpointConfiguration); +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +var host = builder.Build(); +var messageSession = host.Services.GetRequiredService(); +await host.StartAsync(); Console.WriteLine("Press enter to send a message that will throw an exception."); Console.WriteLine("Press any key to exit"); @@ -36,7 +42,7 @@ Id = Guid.NewGuid() }; - await endpointInstance.SendLocal(myMessage); + await messageSession.SendLocal(myMessage); } -await endpointInstance.Stop(); +await host.StopAsync(); diff --git a/samples/errorhandling/Core_10/WithoutDelayedRetries/WithoutDelayedRetries.csproj b/samples/errorhandling/Core_10/WithoutDelayedRetries/WithoutDelayedRetries.csproj index 48c359675f1..59a21997b7d 100644 --- a/samples/errorhandling/Core_10/WithoutDelayedRetries/WithoutDelayedRetries.csproj +++ b/samples/errorhandling/Core_10/WithoutDelayedRetries/WithoutDelayedRetries.csproj @@ -7,7 +7,7 @@ - + diff --git a/samples/faulttolerance/Core_10/Client/Client.csproj b/samples/faulttolerance/Core_10/Client/Client.csproj index 48c359675f1..59a21997b7d 100644 --- a/samples/faulttolerance/Core_10/Client/Client.csproj +++ b/samples/faulttolerance/Core_10/Client/Client.csproj @@ -7,7 +7,7 @@ - + diff --git a/samples/faulttolerance/Core_10/Client/Program.cs b/samples/faulttolerance/Core_10/Client/Program.cs index 8e99d18565a..9d31b4b3fb4 100644 --- a/samples/faulttolerance/Core_10/Client/Program.cs +++ b/samples/faulttolerance/Core_10/Client/Program.cs @@ -1,5 +1,6 @@ using System; -using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NServiceBus; Console.Title = "Client"; @@ -9,7 +10,11 @@ endpointConfiguration.UseSerialization(); endpointConfiguration.UseTransport(new LearningTransport()); -var endpointInstance = await Endpoint.Start(endpointConfiguration); +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +var host = builder.Build(); +var messageSession = host.Services.GetRequiredService(); +await host.StartAsync(); Console.WriteLine("Press enter to send a message"); Console.WriteLine("Press any key to exit"); @@ -28,8 +33,8 @@ Id = id }; - await endpointInstance.Send("Samples.FaultTolerance.Server", myMessage); + await messageSession.Send("Samples.FaultTolerance.Server", myMessage); Console.WriteLine($"Sent a message with id: {id:N}"); } -await endpointInstance.Stop(); +await host.StopAsync(); \ No newline at end of file diff --git a/samples/faulttolerance/Core_10/Server/Program.cs b/samples/faulttolerance/Core_10/Server/Program.cs index 2c343d8f6eb..6a1906b075d 100644 --- a/samples/faulttolerance/Core_10/Server/Program.cs +++ b/samples/faulttolerance/Core_10/Server/Program.cs @@ -24,7 +24,7 @@ Console.ReadKey(); Console.WriteLine("Starting..."); -builder.UseNServiceBus(endpointConfiguration); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); using var app = builder.Build(); await app.RunAsync(); diff --git a/samples/faulttolerance/Core_10/Server/Server.csproj b/samples/faulttolerance/Core_10/Server/Server.csproj index 12e30981188..59a21997b7d 100644 --- a/samples/faulttolerance/Core_10/Server/Server.csproj +++ b/samples/faulttolerance/Core_10/Server/Server.csproj @@ -7,8 +7,7 @@ - - + diff --git a/samples/faulttolerance/Core_10/Shared/Shared.csproj b/samples/faulttolerance/Core_10/Shared/Shared.csproj index 11e2ac7f852..e367cf72d45 100644 --- a/samples/faulttolerance/Core_10/Shared/Shared.csproj +++ b/samples/faulttolerance/Core_10/Shared/Shared.csproj @@ -6,7 +6,7 @@ - + diff --git a/samples/hosting/generic-host/Core_10/GenericHost/GenericHost.csproj b/samples/hosting/generic-host/Core_10/GenericHost/GenericHost.csproj index 7f8d1357625..67ecce690eb 100644 --- a/samples/hosting/generic-host/Core_10/GenericHost/GenericHost.csproj +++ b/samples/hosting/generic-host/Core_10/GenericHost/GenericHost.csproj @@ -8,7 +8,6 @@ - - + \ No newline at end of file diff --git a/samples/hosting/generic-host/Core_10/GenericHost/Program.cs b/samples/hosting/generic-host/Core_10/GenericHost/Program.cs index ccb0244ffad..723b2e19586 100644 --- a/samples/hosting/generic-host/Core_10/GenericHost/Program.cs +++ b/samples/hosting/generic-host/Core_10/GenericHost/Program.cs @@ -11,7 +11,6 @@ endpointConfiguration.UseSerialization(); endpointConfiguration.DefineCriticalErrorAction(OnCriticalError); - // It is recommended to run least privilege and only run installers during deployment. // This also reduces startup time / time to first message. @@ -21,15 +20,15 @@ if (isSetup) { // Provision resources like transport queue creation and persister schemas - await NServiceBus.Installation.Installer.Setup(endpointConfiguration); - return; // Exit application + builder.Services.AddNServiceBusInstallers(configure => + configure.ShutdownBehavior = InstallersShutdownBehavior.StopApplication); } else if (isDevelopment) { endpointConfiguration.EnableInstallers(); } -builder.UseNServiceBus(endpointConfiguration); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); #endregion diff --git a/samples/logging/extensions-logging/Extensions.Logging_4/Sample/Program.cs b/samples/logging/extensions-logging/Extensions.Logging_4/Sample/Program.cs index 2460f672259..5c61d4a44ca 100644 --- a/samples/logging/extensions-logging/Extensions.Logging_4/Sample/Program.cs +++ b/samples/logging/extensions-logging/Extensions.Logging_4/Sample/Program.cs @@ -1,4 +1,6 @@ -using NLog.Config; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using NLog.Config; using NLog.Extensions.Logging; using NLog.Targets; using NServiceBus.Extensions.Logging; @@ -19,13 +21,11 @@ #endregion -#region MicrosoftExtensionsLoggingNLog - -Microsoft.Extensions.Logging.ILoggerFactory extensionsLoggerFactory = new NLogLoggerFactory(); +var builder = Host.CreateApplicationBuilder(); -NServiceBus.Logging.ILoggerFactory nservicebusLoggerFactory = new ExtensionsLoggerFactory(loggerFactory: extensionsLoggerFactory); +#region MicrosoftExtensionsLoggingNLog -NServiceBus.Logging.LogManager.UseFactory(loggerFactory: nservicebusLoggerFactory); +builder.Logging.AddNLog(config); #endregion @@ -34,9 +34,13 @@ endpointConfiguration.UseTransport(); endpointConfiguration.UseSerialization(); -var endpointInstance = await Endpoint.Start(endpointConfiguration); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +var host = builder.Build(); +var messageSession = host.Services.GetRequiredService(); +await host.StartAsync(); + var myMessage = new MyMessage(); -await endpointInstance.SendLocal(myMessage); +await messageSession.SendLocal(myMessage); Console.WriteLine("Press any key to exit"); Console.ReadKey(); -await endpointInstance.Stop(); \ No newline at end of file +await host.StopAsync(); \ No newline at end of file diff --git a/samples/logging/extensions-logging/Extensions.Logging_4/Sample/Sample.csproj b/samples/logging/extensions-logging/Extensions.Logging_4/Sample/Sample.csproj index 1c34b490a88..7c157f73b55 100644 --- a/samples/logging/extensions-logging/Extensions.Logging_4/Sample/Sample.csproj +++ b/samples/logging/extensions-logging/Extensions.Logging_4/Sample/Sample.csproj @@ -8,7 +8,7 @@ - + diff --git a/samples/multi-tenant/di/Core_10/Endpoint/Endpoint.csproj b/samples/multi-tenant/di/Core_10/Endpoint/Endpoint.csproj index add35e653b2..0d2aa9f7a1c 100644 --- a/samples/multi-tenant/di/Core_10/Endpoint/Endpoint.csproj +++ b/samples/multi-tenant/di/Core_10/Endpoint/Endpoint.csproj @@ -5,7 +5,6 @@ 14.0 - - + \ No newline at end of file diff --git a/samples/multi-tenant/di/Core_10/Endpoint/Program.cs b/samples/multi-tenant/di/Core_10/Endpoint/Program.cs index d28a16f4902..0049b463f09 100644 --- a/samples/multi-tenant/di/Core_10/Endpoint/Program.cs +++ b/samples/multi-tenant/di/Core_10/Endpoint/Program.cs @@ -15,19 +15,16 @@ var pipeline = endpointConfiguration.Pipeline; pipeline.Register(new MyUowBehavior(), "Manages the session"); -endpointConfiguration.RegisterComponents(c => -{ - c.AddScoped(); - c.AddScoped(); -}); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + #endregion Console.WriteLine("Press any key, the application is starting"); Console.ReadKey(); Console.WriteLine("Starting..."); -builder.UseNServiceBus(endpointConfiguration); - var host = builder.Build(); await host.StartAsync(); diff --git a/samples/multi-tenant/nhibernate/NHibernate_11/Receiver/Program.cs b/samples/multi-tenant/nhibernate/NHibernate_11/Receiver/Program.cs index 77b714d7175..900d7814552 100644 --- a/samples/multi-tenant/nhibernate/NHibernate_11/Receiver/Program.cs +++ b/samples/multi-tenant/nhibernate/NHibernate_11/Receiver/Program.cs @@ -1,4 +1,5 @@ -using NHibernate.Dialect; +using Microsoft.Extensions.Hosting; +using NHibernate.Dialect; using NHibernate.Driver; using NHibernate.Mapping.ByCode; using NServiceBus.NHibernate; @@ -50,8 +51,6 @@ static async Task Main() pipeline.Register(new StoreTenantIdBehavior(), "Stores tenant ID in the session"); pipeline.Register(new PropagateTenantIdBehavior(), "Propagates tenant ID to outgoing messages"); - var startableEndpoint = await Endpoint.Create(endpointConfiguration); - #region CreateSchema var outboxScript = ScriptGenerator.GenerateOutboxScript(); @@ -80,14 +79,9 @@ static async Task Main() #endregion - var endpointInstance = await startableEndpoint.Start(); - - Console.WriteLine("Press any key to exit"); - Console.ReadKey(); - if (endpointInstance != null) - { - await endpointInstance.Stop(); - } + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + await builder.Build().RunAsync(); } static Configuration CreateNHibernateConfig() diff --git a/samples/multi-tenant/nhibernate/NHibernate_11/Sender/Program.cs b/samples/multi-tenant/nhibernate/NHibernate_11/Sender/Program.cs index e811829dad7..c12d6613aac 100644 --- a/samples/multi-tenant/nhibernate/NHibernate_11/Sender/Program.cs +++ b/samples/multi-tenant/nhibernate/NHibernate_11/Sender/Program.cs @@ -10,7 +10,7 @@ endpointConfiguration.UseSerialization(); var builder = Host.CreateApplicationBuilder(args); -builder.UseNServiceBus(endpointConfiguration); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); var host = builder.Build(); await host.StartAsync(); diff --git a/samples/multi-tenant/nhibernate/NHibernate_11/Sender/Sender.csproj b/samples/multi-tenant/nhibernate/NHibernate_11/Sender/Sender.csproj index 9bb7c2ca6e9..38ccfc73b99 100644 --- a/samples/multi-tenant/nhibernate/NHibernate_11/Sender/Sender.csproj +++ b/samples/multi-tenant/nhibernate/NHibernate_11/Sender/Sender.csproj @@ -11,8 +11,4 @@ - - - - \ No newline at end of file diff --git a/samples/multi-tenant/nhibernate/NHibernate_11/Shared/Shared.csproj b/samples/multi-tenant/nhibernate/NHibernate_11/Shared/Shared.csproj index f444223d49e..f7b480e5612 100644 --- a/samples/multi-tenant/nhibernate/NHibernate_11/Shared/Shared.csproj +++ b/samples/multi-tenant/nhibernate/NHibernate_11/Shared/Shared.csproj @@ -7,8 +7,8 @@ - - + + \ No newline at end of file diff --git a/samples/multi-tenant/propagation/Core_10/Billing/Billing.csproj b/samples/multi-tenant/propagation/Core_10/Billing/Billing.csproj index be0cd76e6b8..0605ffa7af4 100644 --- a/samples/multi-tenant/propagation/Core_10/Billing/Billing.csproj +++ b/samples/multi-tenant/propagation/Core_10/Billing/Billing.csproj @@ -5,9 +5,6 @@ 14.0 enable - - - diff --git a/samples/multi-tenant/propagation/Core_10/Billing/Program.cs b/samples/multi-tenant/propagation/Core_10/Billing/Program.cs index 2485c593d87..5d1741eeb31 100644 --- a/samples/multi-tenant/propagation/Core_10/Billing/Program.cs +++ b/samples/multi-tenant/propagation/Core_10/Billing/Program.cs @@ -12,5 +12,5 @@ pipeline.Register(new StoreTenantIdBehavior(), "Stores tenant ID in the session"); pipeline.Register(new PropagateTenantIdBehavior(), "Propagates tenant ID to outgoing messages"); -builder.UseNServiceBus(endpointConfiguration); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); await builder.Build().RunAsync(); \ No newline at end of file diff --git a/samples/multi-tenant/propagation/Core_10/Client/Program.cs b/samples/multi-tenant/propagation/Core_10/Client/Program.cs index 1b5d299ffcf..79bcb35a953 100644 --- a/samples/multi-tenant/propagation/Core_10/Client/Program.cs +++ b/samples/multi-tenant/propagation/Core_10/Client/Program.cs @@ -1,3 +1,6 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + const string letters = "ABCDEFGHIJKLMNOPQRSTUVXYZ"; var random = new Random(); Console.Title = "Client"; @@ -9,7 +12,11 @@ var routing = endpointConfiguration.UseTransport(new LearningTransport()); routing.RouteToEndpoint(typeof(PlaceOrder), "Samples.MultiTenant.Propagation.Sales"); -var endpointInstance = await Endpoint.Start(endpointConfiguration); +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +var host = builder.Build(); +var messageSession = host.Services.GetRequiredService(); +await host.StartAsync(); Console.WriteLine("Press to send messages"); while (true) @@ -21,7 +28,7 @@ var options = new SendOptions(); options.SetHeader("tenant_id", tenantId); - await endpointInstance.Send(new PlaceOrder(), options); + await messageSession.Send(new PlaceOrder(), options); #endregion diff --git a/samples/multi-tenant/propagation/Core_10/Sales/Program.cs b/samples/multi-tenant/propagation/Core_10/Sales/Program.cs index 7163cce404a..bd919ad89fe 100644 --- a/samples/multi-tenant/propagation/Core_10/Sales/Program.cs +++ b/samples/multi-tenant/propagation/Core_10/Sales/Program.cs @@ -16,5 +16,5 @@ #endregion -builder.UseNServiceBus(endpointConfiguration); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); await builder.Build().RunAsync(); \ No newline at end of file diff --git a/samples/multi-tenant/propagation/Core_10/Sales/Sales.csproj b/samples/multi-tenant/propagation/Core_10/Sales/Sales.csproj index be0cd76e6b8..0605ffa7af4 100644 --- a/samples/multi-tenant/propagation/Core_10/Sales/Sales.csproj +++ b/samples/multi-tenant/propagation/Core_10/Sales/Sales.csproj @@ -5,9 +5,6 @@ 14.0 enable - - - diff --git a/samples/multi-tenant/propagation/Core_10/Shared/Shared.csproj b/samples/multi-tenant/propagation/Core_10/Shared/Shared.csproj index f86974e28bb..5ff580935bf 100644 --- a/samples/multi-tenant/propagation/Core_10/Shared/Shared.csproj +++ b/samples/multi-tenant/propagation/Core_10/Shared/Shared.csproj @@ -5,6 +5,6 @@ enable - + \ No newline at end of file diff --git a/samples/nhibernate/custom-mappings/NHibernate_11/Sample.Attributes/Program.cs b/samples/nhibernate/custom-mappings/NHibernate_11/Sample.Attributes/Program.cs index 7a9fa19c772..054b7f107b3 100644 --- a/samples/nhibernate/custom-mappings/NHibernate_11/Sample.Attributes/Program.cs +++ b/samples/nhibernate/custom-mappings/NHibernate_11/Sample.Attributes/Program.cs @@ -1,5 +1,7 @@ using System; using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NHibernate.Cfg; using NHibernate.Dialect; using NHibernate.Driver; @@ -33,15 +35,20 @@ static async Task Main() var persistence = endpointConfiguration.UsePersistence(); persistence.UseConfiguration(hibernateConfig); - var endpoint = await Endpoint.Start(endpointConfiguration); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + var messageSession = host.Services.GetRequiredService(); + await host.StartAsync(); + var startOrder = new StartOrder { OrderId = "123" }; - await endpoint.SendLocal(startOrder); + await messageSession.SendLocal(startOrder); Console.WriteLine("Press any key to exit"); Console.ReadKey(); - await endpoint.Stop(); + await host.StopAsync(); } #region AttributesConfiguration diff --git a/samples/nhibernate/custom-mappings/NHibernate_11/Sample.Attributes/Sample.Attributes.csproj b/samples/nhibernate/custom-mappings/NHibernate_11/Sample.Attributes/Sample.Attributes.csproj index cf0f338c529..7490a8a8355 100644 --- a/samples/nhibernate/custom-mappings/NHibernate_11/Sample.Attributes/Sample.Attributes.csproj +++ b/samples/nhibernate/custom-mappings/NHibernate_11/Sample.Attributes/Sample.Attributes.csproj @@ -11,6 +11,6 @@ - + \ No newline at end of file diff --git a/samples/nhibernate/custom-mappings/NHibernate_11/Sample.Default/Program.cs b/samples/nhibernate/custom-mappings/NHibernate_11/Sample.Default/Program.cs index 117bf7d9c19..094108312e3 100644 --- a/samples/nhibernate/custom-mappings/NHibernate_11/Sample.Default/Program.cs +++ b/samples/nhibernate/custom-mappings/NHibernate_11/Sample.Default/Program.cs @@ -1,5 +1,7 @@ using System; using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NHibernate.Cfg; using NHibernate.Dialect; using NHibernate.Driver; @@ -30,14 +32,19 @@ static async Task Main() var persistence = endpointConfiguration.UsePersistence(); persistence.UseConfiguration(hibernateConfig); - var endpointInstance = await Endpoint.Start(endpointConfiguration); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + var messageSession = host.Services.GetRequiredService(); + await host.StartAsync(); + var startOrder = new StartOrder { OrderId = "123" }; - await endpointInstance.SendLocal(startOrder); + await messageSession.SendLocal(startOrder); Console.WriteLine("Press any key to exit"); Console.ReadKey(); - await endpointInstance.Stop(); + await host.StopAsync(); } } diff --git a/samples/nhibernate/custom-mappings/NHibernate_11/Sample.Fluent/Program.cs b/samples/nhibernate/custom-mappings/NHibernate_11/Sample.Fluent/Program.cs index 271097f5d7c..790465830a7 100644 --- a/samples/nhibernate/custom-mappings/NHibernate_11/Sample.Fluent/Program.cs +++ b/samples/nhibernate/custom-mappings/NHibernate_11/Sample.Fluent/Program.cs @@ -1,6 +1,8 @@ using System; using System.Threading.Tasks; using FluentNHibernate.Cfg; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NHibernate.Cfg; using NHibernate.Dialect; using NHibernate.Driver; @@ -32,15 +34,20 @@ static async Task Main() var persistence = endpointConfiguration.UsePersistence(); persistence.UseConfiguration(hibernateConfig); - var endpointInstance = await Endpoint.Start(endpointConfiguration); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + var messageSession = host.Services.GetRequiredService(); + await host.StartAsync(); + var startOrder = new StartOrder { OrderId = "123" }; - await endpointInstance.SendLocal(startOrder); + await messageSession.SendLocal(startOrder); Console.WriteLine("Press any key to exit"); Console.ReadKey(); - await endpointInstance.Stop(); + await host.StopAsync(); } #region FluentConfiguration diff --git a/samples/nhibernate/custom-mappings/NHibernate_11/Sample.Fluent/Sample.Fluent.csproj b/samples/nhibernate/custom-mappings/NHibernate_11/Sample.Fluent/Sample.Fluent.csproj index 3ee8d02946e..d253e239b56 100644 --- a/samples/nhibernate/custom-mappings/NHibernate_11/Sample.Fluent/Sample.Fluent.csproj +++ b/samples/nhibernate/custom-mappings/NHibernate_11/Sample.Fluent/Sample.Fluent.csproj @@ -11,6 +11,6 @@ - + \ No newline at end of file diff --git a/samples/nhibernate/custom-mappings/NHibernate_11/Sample.Loquacious/Program.cs b/samples/nhibernate/custom-mappings/NHibernate_11/Sample.Loquacious/Program.cs index f0822dfae03..978368f5ae3 100644 --- a/samples/nhibernate/custom-mappings/NHibernate_11/Sample.Loquacious/Program.cs +++ b/samples/nhibernate/custom-mappings/NHibernate_11/Sample.Loquacious/Program.cs @@ -1,5 +1,7 @@ using System; using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NHibernate.Cfg; using NHibernate.Dialect; using NHibernate.Driver; @@ -33,15 +35,20 @@ static async Task Main() var persistence = endpointConfiguration.UsePersistence(); persistence.UseConfiguration(hibernateConfig); - var endpointInstance = await Endpoint.Start(endpointConfiguration); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + var messageSession = host.Services.GetRequiredService(); + await host.StartAsync(); + var startOrder = new StartOrder { OrderId = "123" }; - await endpointInstance.SendLocal(startOrder); + await messageSession.SendLocal(startOrder); Console.WriteLine("Press any key to exit"); Console.ReadKey(); - await endpointInstance.Stop(); + await host.StopAsync(); } #region LoquaciousConfiguration diff --git a/samples/nhibernate/custom-mappings/NHibernate_11/Sample.XmlMapping/Program.cs b/samples/nhibernate/custom-mappings/NHibernate_11/Sample.XmlMapping/Program.cs index 5ed5922a98c..4d9fe91f9e6 100644 --- a/samples/nhibernate/custom-mappings/NHibernate_11/Sample.XmlMapping/Program.cs +++ b/samples/nhibernate/custom-mappings/NHibernate_11/Sample.XmlMapping/Program.cs @@ -1,6 +1,8 @@ using System; using System.IO; using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NHibernate.Cfg; using NHibernate.Dialect; using NHibernate.Driver; @@ -33,15 +35,20 @@ static async Task Main() var persistence = endpointConfiguration.UsePersistence(); persistence.UseConfiguration(hibernateConfig); - var endpointInstance = await Endpoint.Start(endpointConfiguration); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + var messageSession = host.Services.GetRequiredService(); + await host.StartAsync(); + var startOrder = new StartOrder { OrderId = "123" }; - await endpointInstance.SendLocal(startOrder); + await messageSession.SendLocal(startOrder); Console.WriteLine("Press any key to exit"); Console.ReadKey(); - await endpointInstance.Stop(); + await host.StopAsync(); } #region AddMappingsFromFilesystem diff --git a/samples/nhibernate/custom-mappings/NHibernate_11/Sample.XmlMapping/Sample.XmlMapping.csproj b/samples/nhibernate/custom-mappings/NHibernate_11/Sample.XmlMapping/Sample.XmlMapping.csproj index 39427d69f9c..65bbe1a3fc6 100644 --- a/samples/nhibernate/custom-mappings/NHibernate_11/Sample.XmlMapping/Sample.XmlMapping.csproj +++ b/samples/nhibernate/custom-mappings/NHibernate_11/Sample.XmlMapping/Sample.XmlMapping.csproj @@ -10,7 +10,7 @@ - + diff --git a/samples/nhibernate/custom-mappings/NHibernate_11/Shared/Shared.csproj b/samples/nhibernate/custom-mappings/NHibernate_11/Shared/Shared.csproj index a2f224dbcc9..c30a9c9d8aa 100644 --- a/samples/nhibernate/custom-mappings/NHibernate_11/Shared/Shared.csproj +++ b/samples/nhibernate/custom-mappings/NHibernate_11/Shared/Shared.csproj @@ -4,6 +4,6 @@ 14.0 - + \ No newline at end of file diff --git a/samples/nhibernate/simple/NHibernate_11/Client/Program.cs b/samples/nhibernate/simple/NHibernate_11/Client/Program.cs index 5cfcbdff740..5b1457202b6 100644 --- a/samples/nhibernate/simple/NHibernate_11/Client/Program.cs +++ b/samples/nhibernate/simple/NHibernate_11/Client/Program.cs @@ -1,5 +1,7 @@ using System; using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NServiceBus; Console.Title = "Client"; @@ -8,7 +10,11 @@ endpointConfiguration.UseTransport(new LearningTransport()); endpointConfiguration.UseSerialization(); -var endpointInstance = await Endpoint.Start(endpointConfiguration); +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +var host = builder.Build(); +var messageSession = host.Services.GetRequiredService(); +await host.StartAsync(); Console.WriteLine("Press 'enter' to send a StartOrder messages"); Console.WriteLine("Press any other key to exit"); @@ -28,8 +34,8 @@ { OrderId = orderId }; - await endpointInstance.Send("Samples.NHibernate.Server", startOrder); + await messageSession.Send("Samples.NHibernate.Server", startOrder); Console.WriteLine($"StartOrder Message sent with OrderId {orderId}"); } -await endpointInstance.Stop(); \ No newline at end of file +await host.StopAsync(); \ No newline at end of file diff --git a/samples/nhibernate/simple/NHibernate_11/Server/Program.cs b/samples/nhibernate/simple/NHibernate_11/Server/Program.cs index cdd253d6118..1368df654b8 100644 --- a/samples/nhibernate/simple/NHibernate_11/Server/Program.cs +++ b/samples/nhibernate/simple/NHibernate_11/Server/Program.cs @@ -1,5 +1,7 @@ using System; using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NHibernate.Cfg; using NHibernate.Dialect; using NHibernate.Driver; @@ -34,12 +36,9 @@ endpointConfiguration.EnableInstallers(); endpointConfiguration.UseSerialization(); -var endpointInstance = await Endpoint.Start(endpointConfiguration); - -Console.WriteLine("Press any key to exit"); -Console.ReadKey(); - -await endpointInstance.Stop(); +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +await builder.Build().RunAsync(); static void AddMappings(Configuration nhConfiguration) { diff --git a/samples/nhibernate/simple/NHibernate_11/Server/Server.csproj b/samples/nhibernate/simple/NHibernate_11/Server/Server.csproj index a143ee381bc..b0f4fd32d64 100644 --- a/samples/nhibernate/simple/NHibernate_11/Server/Server.csproj +++ b/samples/nhibernate/simple/NHibernate_11/Server/Server.csproj @@ -10,6 +10,6 @@ - + \ No newline at end of file diff --git a/samples/nhibernate/simple/NHibernate_11/Shared/Shared.csproj b/samples/nhibernate/simple/NHibernate_11/Shared/Shared.csproj index a2f224dbcc9..c30a9c9d8aa 100644 --- a/samples/nhibernate/simple/NHibernate_11/Shared/Shared.csproj +++ b/samples/nhibernate/simple/NHibernate_11/Shared/Shared.csproj @@ -4,6 +4,6 @@ 14.0 - + \ No newline at end of file diff --git a/samples/open-telemetry/application-insights/Core_10/Endpoint/Endpoint.csproj b/samples/open-telemetry/application-insights/Core_10/Endpoint/Endpoint.csproj index b2112ee390a..f31a2ac481e 100644 --- a/samples/open-telemetry/application-insights/Core_10/Endpoint/Endpoint.csproj +++ b/samples/open-telemetry/application-insights/Core_10/Endpoint/Endpoint.csproj @@ -10,7 +10,7 @@ - + diff --git a/samples/open-telemetry/application-insights/Core_10/Endpoint/LoadSimulator.cs b/samples/open-telemetry/application-insights/Core_10/Endpoint/LoadSimulator.cs index 61981a52a53..76eebb48767 100644 --- a/samples/open-telemetry/application-insights/Core_10/Endpoint/LoadSimulator.cs +++ b/samples/open-telemetry/application-insights/Core_10/Endpoint/LoadSimulator.cs @@ -1,16 +1,11 @@ // Simulates busy (almost no delay) / quite time in a sine wave -class LoadSimulator +class LoadSimulator(IMessageSession messageSession, TimeSpan minimumDelay, TimeSpan idleDuration) { - public LoadSimulator(IEndpointInstance endpointInstance, TimeSpan minimumDelay, TimeSpan idleDuration) - { - this.endpointInstance = endpointInstance; - this.minimumDelay = minimumDelay; - this.idleDuration = TimeSpan.FromTicks(idleDuration.Ticks / 2); - } - public void Start(CancellationToken cancellationToken) + public void Start() { - _ = Task.Run(() => Loop(cancellationToken), cancellationToken); + cancellation = new CancellationTokenSource(); + _ = Task.Run(() => Loop(cancellation.Token)); } async Task Loop(CancellationToken cancellationToken) @@ -54,16 +49,12 @@ Task Work(CancellationToken cancellationToken) sendOptions.SetHeader("simulate-failure", bool.TrueString); } - return endpointInstance.Send(new SomeMessage(), sendOptions, cancellationToken); + return messageSession.Send(new SomeMessage(), sendOptions, cancellationToken); } - public Task Stop(CancellationToken cancellationToken) - { - return Task.CompletedTask; - } + public void Stop() => cancellation.Cancel(); + - IEndpointInstance endpointInstance; - TimeSpan minimumDelay; - TimeSpan idleDuration; + CancellationTokenSource cancellation; int index; } \ No newline at end of file diff --git a/samples/open-telemetry/application-insights/Core_10/Endpoint/Program.cs b/samples/open-telemetry/application-insights/Core_10/Endpoint/Program.cs index 2525f244f7a..509d7b44ce4 100644 --- a/samples/open-telemetry/application-insights/Core_10/Endpoint/Program.cs +++ b/samples/open-telemetry/application-insights/Core_10/Endpoint/Program.cs @@ -1,4 +1,6 @@ using Azure.Monitor.OpenTelemetry.Exporter; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using OpenTelemetry; using OpenTelemetry.Resources; using OpenTelemetry.Trace; @@ -43,11 +45,15 @@ var endpointConfiguration = new EndpointConfiguration(endpointName); endpointConfiguration.UseSerialization(); endpointConfiguration.UseTransport(); -var cancellation = new CancellationTokenSource(); -var endpointInstance = await Endpoint.Start(endpointConfiguration, cancellation.Token); -var simulator = new LoadSimulator(endpointInstance, TimeSpan.Zero, TimeSpan.FromSeconds(10)); -simulator.Start(cancellation.Token); +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +var host = builder.Build(); +var messageSession = host.Services.GetRequiredService(); +await host.StartAsync(); + +var simulator = new LoadSimulator(messageSession, TimeSpan.Zero, TimeSpan.FromSeconds(10)); +simulator.Start(); try { @@ -55,13 +61,13 @@ while (Console.ReadKey(true).Key != ConsoleKey.Escape) { - await endpointInstance.SendLocal(new SomeMessage(), cancellation.Token); + await messageSession.SendLocal(new SomeMessage()); } } finally { - await simulator.Stop(cancellation.Token); - await endpointInstance.Stop(cancellation.Token); + simulator.Stop(); + await host.StopAsync(); traceProvider?.Dispose(); meterProvider?.Dispose(); } \ No newline at end of file diff --git a/samples/open-telemetry/customizing/Core_10/Sample/Program.cs b/samples/open-telemetry/customizing/Core_10/Sample/Program.cs index 37720b9f232..fe2fa482aab 100644 --- a/samples/open-telemetry/customizing/Core_10/Sample/Program.cs +++ b/samples/open-telemetry/customizing/Core_10/Sample/Program.cs @@ -1,3 +1,5 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using OpenTelemetry; using OpenTelemetry.Resources; using OpenTelemetry.Trace; @@ -25,7 +27,11 @@ endpointConfiguration.Pipeline.Register(new TraceOutgoingMessageSizeBehavior(), "Captures body size of outgoing messages as OpenTelemetry tags"); endpointConfiguration.Pipeline.Register(new TraceCustomExceptionInHandlerBehavior(), "Captures custom exception and sets reason code as a tag"); -var endpoint = await Endpoint.Start(endpointConfiguration); +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +var host = builder.Build(); +var messageSession = host.Services.GetRequiredService(); +await host.StartAsync(); Console.WriteLine("Endpoint started."); @@ -39,14 +45,14 @@ done = true; break; case ConsoleKey.O: - await endpoint.SendLocal(new CreateOrder { OrderId = Guid.NewGuid() }); + await messageSession.SendLocal(new CreateOrder { OrderId = Guid.NewGuid() }); break; case ConsoleKey.F: - await endpoint.SendLocal(new CreateOrder { OrderId = Guid.NewGuid(), SimulateFailure = true }); + await messageSession.SendLocal(new CreateOrder { OrderId = Guid.NewGuid(), SimulateFailure = true }); break; } } -await endpoint.Stop(); +await host.StopAsync(); Console.WriteLine("Endpoint stopped"); \ No newline at end of file diff --git a/samples/open-telemetry/customizing/Core_10/Sample/Sample.csproj b/samples/open-telemetry/customizing/Core_10/Sample/Sample.csproj index 6a44d38919e..27e9d72a697 100644 --- a/samples/open-telemetry/customizing/Core_10/Sample/Sample.csproj +++ b/samples/open-telemetry/customizing/Core_10/Sample/Sample.csproj @@ -13,7 +13,7 @@ - + diff --git a/samples/open-telemetry/metrics-shim/Core_10/Endpoint/Endpoint.csproj b/samples/open-telemetry/metrics-shim/Core_10/Endpoint/Endpoint.csproj index 311fcd399e9..de1f74f4fc3 100644 --- a/samples/open-telemetry/metrics-shim/Core_10/Endpoint/Endpoint.csproj +++ b/samples/open-telemetry/metrics-shim/Core_10/Endpoint/Endpoint.csproj @@ -10,7 +10,7 @@ - + diff --git a/samples/open-telemetry/metrics-shim/Core_10/Endpoint/LoadSimulator.cs b/samples/open-telemetry/metrics-shim/Core_10/Endpoint/LoadSimulator.cs index 61981a52a53..76eebb48767 100644 --- a/samples/open-telemetry/metrics-shim/Core_10/Endpoint/LoadSimulator.cs +++ b/samples/open-telemetry/metrics-shim/Core_10/Endpoint/LoadSimulator.cs @@ -1,16 +1,11 @@ // Simulates busy (almost no delay) / quite time in a sine wave -class LoadSimulator +class LoadSimulator(IMessageSession messageSession, TimeSpan minimumDelay, TimeSpan idleDuration) { - public LoadSimulator(IEndpointInstance endpointInstance, TimeSpan minimumDelay, TimeSpan idleDuration) - { - this.endpointInstance = endpointInstance; - this.minimumDelay = minimumDelay; - this.idleDuration = TimeSpan.FromTicks(idleDuration.Ticks / 2); - } - public void Start(CancellationToken cancellationToken) + public void Start() { - _ = Task.Run(() => Loop(cancellationToken), cancellationToken); + cancellation = new CancellationTokenSource(); + _ = Task.Run(() => Loop(cancellation.Token)); } async Task Loop(CancellationToken cancellationToken) @@ -54,16 +49,12 @@ Task Work(CancellationToken cancellationToken) sendOptions.SetHeader("simulate-failure", bool.TrueString); } - return endpointInstance.Send(new SomeMessage(), sendOptions, cancellationToken); + return messageSession.Send(new SomeMessage(), sendOptions, cancellationToken); } - public Task Stop(CancellationToken cancellationToken) - { - return Task.CompletedTask; - } + public void Stop() => cancellation.Cancel(); + - IEndpointInstance endpointInstance; - TimeSpan minimumDelay; - TimeSpan idleDuration; + CancellationTokenSource cancellation; int index; } \ No newline at end of file diff --git a/samples/open-telemetry/metrics-shim/Core_10/Endpoint/Program.cs b/samples/open-telemetry/metrics-shim/Core_10/Endpoint/Program.cs index 1b39465af9c..87c4d04ae3a 100644 --- a/samples/open-telemetry/metrics-shim/Core_10/Endpoint/Program.cs +++ b/samples/open-telemetry/metrics-shim/Core_10/Endpoint/Program.cs @@ -1,4 +1,6 @@ using Azure.Monitor.OpenTelemetry.Exporter; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using OpenTelemetry; using OpenTelemetry.Resources; using OpenTelemetry.Metrics; @@ -33,11 +35,14 @@ endpointConfiguration.UseTransport(); endpointConfiguration.EnableFeature(); -var cancellation = new CancellationTokenSource(); -var endpointInstance = await Endpoint.Start(endpointConfiguration, cancellation.Token); +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +var host = builder.Build(); +var messageSession = host.Services.GetRequiredService(); +await host.StartAsync(); -var simulator = new LoadSimulator(endpointInstance, TimeSpan.Zero, TimeSpan.FromSeconds(10)); -simulator.Start(cancellation.Token); +var simulator = new LoadSimulator(messageSession, TimeSpan.Zero, TimeSpan.FromSeconds(10)); +simulator.Start(); try { @@ -45,12 +50,12 @@ while (Console.ReadKey(true).Key != ConsoleKey.Escape) { - await endpointInstance.SendLocal(new SomeMessage(), cancellation.Token); + await messageSession.SendLocal(new SomeMessage()); } } finally { - await simulator.Stop(cancellation.Token); - await endpointInstance.Stop(cancellation.Token); + simulator.Stop(); + await host.StopAsync(); meterProvider?.Dispose(); } \ No newline at end of file diff --git a/samples/open-telemetry/prometheus-grafana/Core_10/Endpoint/Endpoint.csproj b/samples/open-telemetry/prometheus-grafana/Core_10/Endpoint/Endpoint.csproj index 64ffb5170c9..f71d4d370ec 100644 --- a/samples/open-telemetry/prometheus-grafana/Core_10/Endpoint/Endpoint.csproj +++ b/samples/open-telemetry/prometheus-grafana/Core_10/Endpoint/Endpoint.csproj @@ -8,7 +8,7 @@ - + diff --git a/samples/open-telemetry/prometheus-grafana/Core_10/Endpoint/LoadSimulator.cs b/samples/open-telemetry/prometheus-grafana/Core_10/Endpoint/LoadSimulator.cs index 61981a52a53..76eebb48767 100644 --- a/samples/open-telemetry/prometheus-grafana/Core_10/Endpoint/LoadSimulator.cs +++ b/samples/open-telemetry/prometheus-grafana/Core_10/Endpoint/LoadSimulator.cs @@ -1,16 +1,11 @@ // Simulates busy (almost no delay) / quite time in a sine wave -class LoadSimulator +class LoadSimulator(IMessageSession messageSession, TimeSpan minimumDelay, TimeSpan idleDuration) { - public LoadSimulator(IEndpointInstance endpointInstance, TimeSpan minimumDelay, TimeSpan idleDuration) - { - this.endpointInstance = endpointInstance; - this.minimumDelay = minimumDelay; - this.idleDuration = TimeSpan.FromTicks(idleDuration.Ticks / 2); - } - public void Start(CancellationToken cancellationToken) + public void Start() { - _ = Task.Run(() => Loop(cancellationToken), cancellationToken); + cancellation = new CancellationTokenSource(); + _ = Task.Run(() => Loop(cancellation.Token)); } async Task Loop(CancellationToken cancellationToken) @@ -54,16 +49,12 @@ Task Work(CancellationToken cancellationToken) sendOptions.SetHeader("simulate-failure", bool.TrueString); } - return endpointInstance.Send(new SomeMessage(), sendOptions, cancellationToken); + return messageSession.Send(new SomeMessage(), sendOptions, cancellationToken); } - public Task Stop(CancellationToken cancellationToken) - { - return Task.CompletedTask; - } + public void Stop() => cancellation.Cancel(); + - IEndpointInstance endpointInstance; - TimeSpan minimumDelay; - TimeSpan idleDuration; + CancellationTokenSource cancellation; int index; } \ No newline at end of file diff --git a/samples/open-telemetry/prometheus-grafana/Core_10/Endpoint/Program.cs b/samples/open-telemetry/prometheus-grafana/Core_10/Endpoint/Program.cs index f7f5f689758..62b2fb6e78f 100644 --- a/samples/open-telemetry/prometheus-grafana/Core_10/Endpoint/Program.cs +++ b/samples/open-telemetry/prometheus-grafana/Core_10/Endpoint/Program.cs @@ -1,3 +1,5 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using OpenTelemetry; using OpenTelemetry.Metrics; using OpenTelemetry.Resources; @@ -33,13 +35,16 @@ public static async Task Main() endpointConfiguration.UseSerialization(); endpointConfiguration.UseTransport(); - var cancellation = new CancellationTokenSource(); - var endpointInstance = await Endpoint.Start(endpointConfiguration, cancellation.Token); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + var messageSession = host.Services.GetRequiredService(); + await host.StartAsync(); #region prometheus-load-simulator - var simulator = new LoadSimulator(endpointInstance, TimeSpan.Zero, TimeSpan.FromSeconds(10)); - simulator.Start(cancellation.Token); + var simulator = new LoadSimulator(messageSession, TimeSpan.Zero, TimeSpan.FromSeconds(10)); + simulator.Start(); #endregion @@ -50,13 +55,13 @@ public static async Task Main() while (Console.ReadKey(true).Key != ConsoleKey.Escape) { - await endpointInstance.SendLocal(new SomeMessage(), cancellation.Token); + await messageSession.SendLocal(new SomeMessage()); } } finally { - await simulator.Stop(cancellation.Token); - await endpointInstance.Stop(cancellation.Token); + simulator.Stop(); + await host.StopAsync(); meterProvider?.Dispose(); } } diff --git a/samples/outbox/cosmosdb/Core_10/Sample/Program.cs b/samples/outbox/cosmosdb/Core_10/Sample/Program.cs index b0dcf69a7b7..85794b7328a 100644 --- a/samples/outbox/cosmosdb/Core_10/Sample/Program.cs +++ b/samples/outbox/cosmosdb/Core_10/Sample/Program.cs @@ -1,6 +1,8 @@ using System; using System.Threading.Tasks; using Microsoft.Azure.Cosmos; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NServiceBus; class Program @@ -55,7 +57,12 @@ static async Task Main() endpointConfiguration.LimitMessageProcessingConcurrencyTo(1); #endregion - var endpointInstance = await Endpoint.Start(endpointConfiguration); + + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + var messageSession = host.Services.GetRequiredService(); + await host.StartAsync(); Console.WriteLine("Endpoint started. Press Enter to send 5 sets of duplicate messages..."); Console.ReadLine(); @@ -63,12 +70,12 @@ static async Task Main() for (var i = 0; i < 5; i++) { var myMessage = new MyMessage(); - await Helper.SendDuplicates(endpointInstance, myMessage, totalCount: 2); + await Helper.SendDuplicates(messageSession, myMessage, totalCount: 2); } await Task.Delay(5000); Console.WriteLine("Press any key to exit"); Console.ReadKey(); - await endpointInstance.Stop(); + await host.StopAsync(); } } diff --git a/samples/outbox/cosmosdb/Core_10/Sample/Sample.csproj b/samples/outbox/cosmosdb/Core_10/Sample/Sample.csproj index 5bcab5350fe..18514f92882 100644 --- a/samples/outbox/cosmosdb/Core_10/Sample/Sample.csproj +++ b/samples/outbox/cosmosdb/Core_10/Sample/Sample.csproj @@ -5,7 +5,7 @@ 14.0 - + diff --git a/samples/outbox/mongodb/Core_10/Sample/Program.cs b/samples/outbox/mongodb/Core_10/Sample/Program.cs index 424eee9ab14..fbf63883a41 100644 --- a/samples/outbox/mongodb/Core_10/Sample/Program.cs +++ b/samples/outbox/mongodb/Core_10/Sample/Program.cs @@ -1,5 +1,7 @@ using System; using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using MongoDB.Driver; using NServiceBus; @@ -41,7 +43,12 @@ static async Task Main() endpointConfiguration.LimitMessageProcessingConcurrencyTo(1); #endregion - var endpointInstance = await Endpoint.Start(endpointConfiguration); + + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + var messageSession = host.Services.GetRequiredService(); + await host.StartAsync(); Console.WriteLine("Endpoint started. Press Enter to send 5 sets of duplicate messages..."); Console.ReadLine(); @@ -49,12 +56,12 @@ static async Task Main() for (var i = 0; i < 5; i++) { var myMessage = new MyMessage(); - await Helper.SendDuplicates(endpointInstance, myMessage, totalCount: 2); + await Helper.SendDuplicates(messageSession, myMessage, totalCount: 2); } await Task.Delay(5000); Console.WriteLine("Press any key to exit"); Console.ReadKey(); - await endpointInstance.Stop(); + await host.StopAsync(); } } diff --git a/samples/outbox/mongodb/Core_10/Sample/Sample.csproj b/samples/outbox/mongodb/Core_10/Sample/Sample.csproj index 6d6abf0e2d0..d6440f81933 100644 --- a/samples/outbox/mongodb/Core_10/Sample/Sample.csproj +++ b/samples/outbox/mongodb/Core_10/Sample/Sample.csproj @@ -5,7 +5,7 @@ 14.0 - + diff --git a/samples/outbox/rabbit/Core_10/Sample/Program.cs b/samples/outbox/rabbit/Core_10/Sample/Program.cs index 477792286ef..772e7cc619e 100644 --- a/samples/outbox/rabbit/Core_10/Sample/Program.cs +++ b/samples/outbox/rabbit/Core_10/Sample/Program.cs @@ -1,6 +1,8 @@ using System; using System.Threading.Tasks; using Microsoft.Data.SqlClient; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NServiceBus; class Program @@ -47,7 +49,11 @@ static async Task Main() Helper.EnsureDatabaseExists(connectionString); - var endpointInstance = await Endpoint.Start(endpointConfiguration); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + var messageSession = host.Services.GetRequiredService(); + await host.StartAsync(); Console.WriteLine("Endpoint started. Press Enter to send 5 sets of duplicate messages..."); Console.ReadLine(); @@ -55,12 +61,12 @@ static async Task Main() for (var i = 0; i < 5; i++) { var myMessage = new MyMessage(); - await Helper.SendDuplicates(endpointInstance, myMessage, totalCount: 2); + await Helper.SendDuplicates(messageSession, myMessage, totalCount: 2); } await Task.Delay(5000); Console.WriteLine("Press any key to exit"); Console.ReadKey(); - await endpointInstance.Stop(); + await host.StopAsync(); } } diff --git a/samples/outbox/rabbit/Core_10/Sample/Sample.csproj b/samples/outbox/rabbit/Core_10/Sample/Sample.csproj index bd76d86a3d8..0d2fd0eb261 100644 --- a/samples/outbox/rabbit/Core_10/Sample/Sample.csproj +++ b/samples/outbox/rabbit/Core_10/Sample/Sample.csproj @@ -5,7 +5,7 @@ 14.0 - + diff --git a/samples/pipeline/fix-messages-using-behavior/Core_10/Receiver/Program.cs b/samples/pipeline/fix-messages-using-behavior/Core_10/Receiver/Program.cs index 8a4e31a2a05..5385608b170 100644 --- a/samples/pipeline/fix-messages-using-behavior/Core_10/Receiver/Program.cs +++ b/samples/pipeline/fix-messages-using-behavior/Core_10/Receiver/Program.cs @@ -1,3 +1,6 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + Console.Title = "Receiver"; var endpointConfiguration = new EndpointConfiguration("FixMalformedMessages.Receiver"); @@ -33,9 +36,12 @@ #endregion -var endpointInstance = await Endpoint.Start(endpointConfiguration); +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +var host = builder.Build(); +await host.StartAsync(); Console.WriteLine("Press 'Enter' to finish."); Console.ReadLine(); -await endpointInstance.Stop(); +await host.StopAsync(); diff --git a/samples/pipeline/fix-messages-using-behavior/Core_10/Sender/Program.cs b/samples/pipeline/fix-messages-using-behavior/Core_10/Sender/Program.cs index 85353d609c5..e12db889ff5 100644 --- a/samples/pipeline/fix-messages-using-behavior/Core_10/Sender/Program.cs +++ b/samples/pipeline/fix-messages-using-behavior/Core_10/Sender/Program.cs @@ -1,3 +1,6 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + Console.Title = "Sender"; var endpointConfiguration = new EndpointConfiguration("FixMalformedMessages.Sender"); @@ -8,7 +11,11 @@ var routing = endpointConfiguration.UseTransport(new LearningTransport()); routing.RouteToEndpoint(typeof(SimpleMessage), "FixMalformedMessages.Receiver"); -var endpointInstance = await Endpoint.Start(endpointConfiguration); +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +var host = builder.Build(); +var messageSession = host.Services.GetRequiredService(); +await host.StartAsync(); Console.WriteLine("Press 'Enter' to send a new message. Press any other key to finish."); while (true) @@ -26,11 +33,11 @@ { Id = guid.ToString().ToLowerInvariant() }; - await endpointInstance.Send(simpleMessage); + await messageSession.Send(simpleMessage); Console.WriteLine($"Sent a new message with Id = {guid}."); Console.WriteLine("Press 'Enter' to send a new message. Press any other key to finish."); } -await endpointInstance.Stop(); +await host.StopAsync(); diff --git a/samples/pipeline/fix-messages-using-behavior/Core_10/Shared/Shared.csproj b/samples/pipeline/fix-messages-using-behavior/Core_10/Shared/Shared.csproj index f86974e28bb..5ff580935bf 100644 --- a/samples/pipeline/fix-messages-using-behavior/Core_10/Shared/Shared.csproj +++ b/samples/pipeline/fix-messages-using-behavior/Core_10/Shared/Shared.csproj @@ -5,6 +5,6 @@ enable - + \ No newline at end of file diff --git a/samples/pipeline/header-propagation/Core_10/Messages/Messages.csproj b/samples/pipeline/header-propagation/Core_10/Messages/Messages.csproj index 11e2ac7f852..e367cf72d45 100644 --- a/samples/pipeline/header-propagation/Core_10/Messages/Messages.csproj +++ b/samples/pipeline/header-propagation/Core_10/Messages/Messages.csproj @@ -6,7 +6,7 @@ - + diff --git a/samples/pipeline/header-propagation/Core_10/Receiver/Program.cs b/samples/pipeline/header-propagation/Core_10/Receiver/Program.cs index 7d587e21cb4..a7e173e3297 100644 --- a/samples/pipeline/header-propagation/Core_10/Receiver/Program.cs +++ b/samples/pipeline/header-propagation/Core_10/Receiver/Program.cs @@ -1,5 +1,7 @@ using System; using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NServiceBus; public static class Program @@ -19,7 +21,10 @@ public static async Task Main() ); #endregion - var endpoint = await Endpoint.Start(endpointConfiguration); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + await host.StartAsync(); Console.WriteLine("Press [ESC] to quit."); @@ -27,7 +32,7 @@ public static async Task Main() { } - await endpoint.Stop(); + await host.StopAsync(); } } diff --git a/samples/pipeline/header-propagation/Core_10/Sender/Program.cs b/samples/pipeline/header-propagation/Core_10/Sender/Program.cs index 854a807d6c4..79c70145ed7 100644 --- a/samples/pipeline/header-propagation/Core_10/Sender/Program.cs +++ b/samples/pipeline/header-propagation/Core_10/Sender/Program.cs @@ -1,5 +1,7 @@ using System; using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NServiceBus; public static class Program @@ -14,7 +16,11 @@ public static async Task Main() transport.Routing().RouteToEndpoint(typeof(ProcessOrder), "Receiver"); - var endpoint = await Endpoint.Start(endpointConfiguration); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + var messageSession = host.Services.GetRequiredService(); + await host.StartAsync(); Console.WriteLine("Press [ESC] to quit. Any other key to send a message."); @@ -25,11 +31,11 @@ public static async Task Main() var sendOptions = new SendOptions(); sendOptions.SetHeader("CustomerId", customerId); - await endpoint.Send(new ProcessOrder(), sendOptions); + await messageSession.Send(new ProcessOrder(), sendOptions); Console.WriteLine($"Message sent, customerId = {customerId}."); #endregion } - await endpoint.Stop(); + await host.StopAsync(); } } diff --git a/samples/pipeline/message-signing/Core_10/ReceivingEndpoint/Program.cs b/samples/pipeline/message-signing/Core_10/ReceivingEndpoint/Program.cs index 6e3879b8192..0cd8c9266f6 100644 --- a/samples/pipeline/message-signing/Core_10/ReceivingEndpoint/Program.cs +++ b/samples/pipeline/message-signing/Core_10/ReceivingEndpoint/Program.cs @@ -14,5 +14,5 @@ endpointConfiguration.RegisterSigningBehaviors(); Console.WriteLine("Waiting to receive messages. Press Enter to exit."); -builder.UseNServiceBus(endpointConfiguration); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); await builder.Build().RunAsync(); diff --git a/samples/pipeline/message-signing/Core_10/ReceivingEndpoint/ReceivingEndpoint.csproj b/samples/pipeline/message-signing/Core_10/ReceivingEndpoint/ReceivingEndpoint.csproj index 95a761ec308..c9a0e455c34 100644 --- a/samples/pipeline/message-signing/Core_10/ReceivingEndpoint/ReceivingEndpoint.csproj +++ b/samples/pipeline/message-signing/Core_10/ReceivingEndpoint/ReceivingEndpoint.csproj @@ -4,9 +4,6 @@ 14.0 net10.0 - - - diff --git a/samples/pipeline/message-signing/Core_10/Shared/Shared.csproj b/samples/pipeline/message-signing/Core_10/Shared/Shared.csproj index 3020b3fdb48..f9c512171e0 100644 --- a/samples/pipeline/message-signing/Core_10/Shared/Shared.csproj +++ b/samples/pipeline/message-signing/Core_10/Shared/Shared.csproj @@ -4,6 +4,6 @@ net10.0 - + \ No newline at end of file diff --git a/samples/pipeline/message-signing/Core_10/SignedSender/Program.cs b/samples/pipeline/message-signing/Core_10/SignedSender/Program.cs index 15fa38b6c92..00f4a47159a 100644 --- a/samples/pipeline/message-signing/Core_10/SignedSender/Program.cs +++ b/samples/pipeline/message-signing/Core_10/SignedSender/Program.cs @@ -1,5 +1,7 @@ using System; using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NServiceBus; class Program @@ -21,7 +23,11 @@ static async Task Main() #endregion - var endpointInstance = await Endpoint.Start(endpointConfiguration); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + var messageSession = host.Services.GetRequiredService(); + await host.StartAsync(); var key = default(ConsoleKeyInfo); @@ -31,9 +37,9 @@ static async Task Main() key = Console.ReadKey(); var message = new MyMessage { Contents = Guid.NewGuid().ToString() }; - await endpointInstance.Send(message); + await messageSession.Send(message); } - await endpointInstance.Stop(); + await host.StopAsync(); } } diff --git a/samples/pipeline/message-signing/Core_10/UnsignedSender/Program.cs b/samples/pipeline/message-signing/Core_10/UnsignedSender/Program.cs index e2188fd3406..9bbb5e5418c 100644 --- a/samples/pipeline/message-signing/Core_10/UnsignedSender/Program.cs +++ b/samples/pipeline/message-signing/Core_10/UnsignedSender/Program.cs @@ -1,5 +1,7 @@ using System; using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NServiceBus; class Program @@ -18,7 +20,11 @@ static async Task Main() // This endpoint does not sign messages. // Do not call endpointConfiguration.RegisterSigningBehaviors() here. - var endpointInstance = await Endpoint.Start(endpointConfiguration); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + var messageSession = host.Services.GetRequiredService(); + await host.StartAsync(); var key = default(ConsoleKeyInfo); @@ -30,9 +36,9 @@ static async Task Main() var options = new SendOptions(); options.SetHeader("X-Message-Header", "Fake signature, obviously not correct!"); var message = new MyMessage { Contents = Guid.NewGuid().ToString() }; - await endpointInstance.Send(message, options); + await messageSession.Send(message, options); } - await endpointInstance.Stop(); + await host.StopAsync(); } } diff --git a/samples/platform-connector/code-first/PlatformConnector_4/Endpoint/Endpoint.csproj b/samples/platform-connector/code-first/PlatformConnector_4/Endpoint/Endpoint.csproj index 0304ec73252..022e4ea111d 100644 --- a/samples/platform-connector/code-first/PlatformConnector_4/Endpoint/Endpoint.csproj +++ b/samples/platform-connector/code-first/PlatformConnector_4/Endpoint/Endpoint.csproj @@ -6,7 +6,7 @@ enable - + diff --git a/samples/platform-connector/code-first/PlatformConnector_4/Endpoint/Program.cs b/samples/platform-connector/code-first/PlatformConnector_4/Endpoint/Program.cs index 263fafb0114..b5f65c8e210 100644 --- a/samples/platform-connector/code-first/PlatformConnector_4/Endpoint/Program.cs +++ b/samples/platform-connector/code-first/PlatformConnector_4/Endpoint/Program.cs @@ -1,3 +1,6 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + Console.Title = "Endpoint"; var endpointConfiguration = new EndpointConfiguration("Endpoint"); @@ -45,14 +48,18 @@ endpointConfiguration.ConnectToServicePlatform(platformConnection); #endregion -var endpoint = await Endpoint.Start(endpointConfiguration); +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +var host = builder.Build(); +var messageSession = host.Services.GetRequiredService(); +await host.StartAsync(); Console.WriteLine("Press any key to send a message, ESC to stop"); while (Console.ReadKey(true).Key != ConsoleKey.Escape) { - await endpoint.SendLocal(new BusinessMessage { BusinessId = Guid.NewGuid() }); + await messageSession.SendLocal(new BusinessMessage { BusinessId = Guid.NewGuid() }); Console.WriteLine("Message sent"); } -await endpoint.Stop(); \ No newline at end of file +await host.StopAsync(); \ No newline at end of file diff --git a/samples/platform-connector/json/PlatformConnector_4/Endpoint/Endpoint.csproj b/samples/platform-connector/json/PlatformConnector_4/Endpoint/Endpoint.csproj index cebd05d21f7..9f82ef5d26d 100644 --- a/samples/platform-connector/json/PlatformConnector_4/Endpoint/Endpoint.csproj +++ b/samples/platform-connector/json/PlatformConnector_4/Endpoint/Endpoint.csproj @@ -9,7 +9,7 @@ - + diff --git a/samples/platform-connector/json/PlatformConnector_4/Endpoint/Program.cs b/samples/platform-connector/json/PlatformConnector_4/Endpoint/Program.cs index 4567990d134..9e823aab259 100644 --- a/samples/platform-connector/json/PlatformConnector_4/Endpoint/Program.cs +++ b/samples/platform-connector/json/PlatformConnector_4/Endpoint/Program.cs @@ -1,3 +1,6 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + Console.Title = "Endpoint"; var endpointConfiguration = new EndpointConfiguration("Endpoint"); @@ -16,14 +19,18 @@ endpointConfiguration.ConnectToServicePlatform(platformConnection); #endregion -var endpoint = await Endpoint.Start(endpointConfiguration); +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +var host = builder.Build(); +var messageSession = host.Services.GetRequiredService(); +await host.StartAsync(); Console.WriteLine("Press any key to send a message, ESC to stop"); while (Console.ReadKey(true).Key != ConsoleKey.Escape) { - await endpoint.SendLocal(new BusinessMessage { BusinessId = Guid.NewGuid() }); + await messageSession.SendLocal(new BusinessMessage { BusinessId = Guid.NewGuid() }); Console.WriteLine("Message sent"); } -await endpoint.Stop(); +await host.StopAsync(); diff --git a/samples/rabbitmq/simple/Rabbit_11/Receiver/Program.cs b/samples/rabbitmq/simple/Rabbit_11/Receiver/Program.cs index 626579866b4..b8626721442 100644 --- a/samples/rabbitmq/simple/Rabbit_11/Receiver/Program.cs +++ b/samples/rabbitmq/simple/Rabbit_11/Receiver/Program.cs @@ -10,5 +10,5 @@ transport.ConnectionString("host=localhost"); endpointConfiguration.EnableInstallers(); -builder.UseNServiceBus(endpointConfiguration); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); await builder.Build().RunAsync(); \ No newline at end of file diff --git a/samples/rabbitmq/simple/Rabbit_11/Receiver/Receiver.csproj b/samples/rabbitmq/simple/Rabbit_11/Receiver/Receiver.csproj index c488ee6c981..68b010a6c70 100644 --- a/samples/rabbitmq/simple/Rabbit_11/Receiver/Receiver.csproj +++ b/samples/rabbitmq/simple/Rabbit_11/Receiver/Receiver.csproj @@ -13,7 +13,6 @@ - diff --git a/samples/rabbitmq/simple/Rabbit_11/Sender/Program.cs b/samples/rabbitmq/simple/Rabbit_11/Sender/Program.cs index 03c5d3b94ce..2d79a78b3e0 100644 --- a/samples/rabbitmq/simple/Rabbit_11/Sender/Program.cs +++ b/samples/rabbitmq/simple/Rabbit_11/Sender/Program.cs @@ -1,4 +1,6 @@ -using Shared; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Shared; Console.Title = "SimpleSender"; @@ -13,9 +15,14 @@ transport.Routing().RouteToEndpoint(typeof(MyCommand), "Samples.RabbitMQ.SimpleReceiver"); endpointConfiguration.EnableInstallers(); -var endpointInstance = await Endpoint.Start(endpointConfiguration); -await SendMessages(endpointInstance); -await endpointInstance.Stop(); +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +var host = builder.Build(); +var messageSession = host.Services.GetRequiredService(); +await host.StartAsync(); + +await SendMessages(messageSession); +await host.StopAsync(); static async Task SendMessages(IMessageSession messageSession) { diff --git a/samples/rabbitmq/simple/Rabbit_11/Shared/Shared.csproj b/samples/rabbitmq/simple/Rabbit_11/Shared/Shared.csproj index bf2384a08ed..224d26fc0cb 100644 --- a/samples/rabbitmq/simple/Rabbit_11/Shared/Shared.csproj +++ b/samples/rabbitmq/simple/Rabbit_11/Shared/Shared.csproj @@ -8,7 +8,7 @@ - + \ No newline at end of file diff --git a/samples/routing/message-forwarding/Core_10/Messages/Messages.csproj b/samples/routing/message-forwarding/Core_10/Messages/Messages.csproj index a2f224dbcc9..c30a9c9d8aa 100644 --- a/samples/routing/message-forwarding/Core_10/Messages/Messages.csproj +++ b/samples/routing/message-forwarding/Core_10/Messages/Messages.csproj @@ -4,6 +4,6 @@ 14.0 - + \ No newline at end of file diff --git a/samples/routing/message-forwarding/Core_10/NServiceBus.MessageForwarding/NServiceBus.MessageForwarding.csproj b/samples/routing/message-forwarding/Core_10/NServiceBus.MessageForwarding/NServiceBus.MessageForwarding.csproj index a2f224dbcc9..c30a9c9d8aa 100644 --- a/samples/routing/message-forwarding/Core_10/NServiceBus.MessageForwarding/NServiceBus.MessageForwarding.csproj +++ b/samples/routing/message-forwarding/Core_10/NServiceBus.MessageForwarding/NServiceBus.MessageForwarding.csproj @@ -4,6 +4,6 @@ 14.0 - + \ No newline at end of file diff --git a/samples/routing/message-forwarding/Core_10/OriginalDestination/Program.cs b/samples/routing/message-forwarding/Core_10/OriginalDestination/Program.cs index da26ca0642c..583a701789b 100644 --- a/samples/routing/message-forwarding/Core_10/OriginalDestination/Program.cs +++ b/samples/routing/message-forwarding/Core_10/OriginalDestination/Program.cs @@ -1,23 +1,20 @@ using System; +using Microsoft.Extensions.Hosting; using NServiceBus; Console.Title = "OriginalDestination"; #region forward-messages-after-processing -var config = new EndpointConfiguration("OriginalDestination"); -config.UseTransport(new LearningTransport()); +var endpointConfiguration = new EndpointConfiguration("OriginalDestination"); +endpointConfiguration.UseTransport(new LearningTransport()); -config.ForwardMessagesAfterProcessingTo("UpgradedDestination"); +endpointConfiguration.ForwardMessagesAfterProcessingTo("UpgradedDestination"); #endregion -config.UseSerialization(); +endpointConfiguration.UseSerialization(); -var endpoint = await Endpoint.Start(config); - -Console.WriteLine("Endpoint Started. Press any key to exit"); - -Console.ReadKey(); - -await endpoint.Stop(); \ No newline at end of file +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +await builder.Build().StartAsync(); diff --git a/samples/routing/message-forwarding/Core_10/Sender/Program.cs b/samples/routing/message-forwarding/Core_10/Sender/Program.cs index 7971fbb5d94..88d5f7fd8d1 100644 --- a/samples/routing/message-forwarding/Core_10/Sender/Program.cs +++ b/samples/routing/message-forwarding/Core_10/Sender/Program.cs @@ -1,21 +1,27 @@ using System; using Messages; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NServiceBus; Console.Title = "Sender"; #region route-message-to-original-destination -var config = new EndpointConfiguration("Sender"); -var routing = config.UseTransport(new LearningTransport()); +var endpointConfiguration = new EndpointConfiguration("Sender"); +var routing = endpointConfiguration.UseTransport(new LearningTransport()); routing.RouteToEndpoint(typeof(ImportantMessage), "OriginalDestination"); #endregion -config.UseSerialization(); +endpointConfiguration.UseSerialization(); -var endpoint = await Endpoint.Start(config); +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +var host = builder.Build(); +var messageSession = host.Services.GetRequiredService(); +await host.StartAsync(); Console.WriteLine("Endpoint Started. Press s to send a very important message. Any other key to exit"); @@ -27,8 +33,8 @@ { Text = $"Hello there: {i++}" }; - await endpoint.Send(message); + await messageSession.Send(message); Console.WriteLine("Message sent"); } -await endpoint.Stop(); \ No newline at end of file +await host.StopAsync(); \ No newline at end of file diff --git a/samples/routing/message-forwarding/Core_10/UpgradedDestination/Program.cs b/samples/routing/message-forwarding/Core_10/UpgradedDestination/Program.cs index ecf838a0c66..640a2286221 100644 --- a/samples/routing/message-forwarding/Core_10/UpgradedDestination/Program.cs +++ b/samples/routing/message-forwarding/Core_10/UpgradedDestination/Program.cs @@ -1,15 +1,12 @@ using System; +using Microsoft.Extensions.Hosting; using NServiceBus; Console.Title = "UpgradedDestination"; -var config = new EndpointConfiguration("UpgradedDestination"); -config.UseSerialization(); -config.UseTransport(new LearningTransport()); +var endpointConfiguration = new EndpointConfiguration("UpgradedDestination"); +endpointConfiguration.UseSerialization(); +endpointConfiguration.UseTransport(new LearningTransport()); -var endpoint = await Endpoint.Start(config); - -Console.WriteLine("Endpoint Started. Press any key to exit"); - -Console.ReadKey(); - -await endpoint.Stop(); \ No newline at end of file +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +await builder.Build().StartAsync(); diff --git a/samples/saga/batching/Core_10/SharedMessages/Routing.cs b/samples/saga/batching/Core_10/SharedMessages/RoutingHelper.cs similarity index 60% rename from samples/saga/batching/Core_10/SharedMessages/Routing.cs rename to samples/saga/batching/Core_10/SharedMessages/RoutingHelper.cs index d87f1f4fa19..7ccc83951ce 100644 --- a/samples/saga/batching/Core_10/SharedMessages/Routing.cs +++ b/samples/saga/batching/Core_10/SharedMessages/RoutingHelper.cs @@ -1,15 +1,12 @@ -using System.Threading.Tasks; using NServiceBus; -public static class Endpoint +public static class RoutingHelper { - public static Task StartWithDefaultRoutes(this EndpointConfiguration config, RoutingSettings routing) + public static void ApplyDefaultRouting(RoutingSettings routing) { routing.RouteToEndpoint(typeof(StartProcessing), EndpointNames.WorkGenerator); routing.RouteToEndpoint(typeof(WorkOrderCompleted), EndpointNames.WorkGenerator); routing.RouteToEndpoint(typeof(WorkAllDone), EndpointNames.WorkGenerator); routing.RouteToEndpoint(typeof(ProcessWorkOrder), EndpointNames.WorkProcessor); - - return NServiceBus.Endpoint.Start(config); } } \ No newline at end of file diff --git a/samples/saga/batching/Core_10/SharedMessages/SharedMessages.csproj b/samples/saga/batching/Core_10/SharedMessages/SharedMessages.csproj index 11e2ac7f852..e367cf72d45 100644 --- a/samples/saga/batching/Core_10/SharedMessages/SharedMessages.csproj +++ b/samples/saga/batching/Core_10/SharedMessages/SharedMessages.csproj @@ -6,7 +6,7 @@ - + diff --git a/samples/saga/batching/Core_10/WorkGenerator/Program.cs b/samples/saga/batching/Core_10/WorkGenerator/Program.cs index 6e0bb23177f..4073faf3c1b 100644 --- a/samples/saga/batching/Core_10/WorkGenerator/Program.cs +++ b/samples/saga/batching/Core_10/WorkGenerator/Program.cs @@ -1,53 +1,62 @@ using System; using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NServiceBus; -public static class Program -{ - public static async Task Main() - { - var config = new EndpointConfiguration(EndpointNames.WorkGenerator); +var config = new EndpointConfiguration(EndpointNames.WorkGenerator); + +config.UsePersistence(); +config.UseSerialization(); +config.AuditProcessedMessagesTo("audit"); +config.SendFailedMessagesTo("error"); + +var transport = config.UseTransport(); +var routing = transport.Routing(); +RoutingHelper.ApplyDefaultRouting(routing); - config.UsePersistence(); - config.UseSerialization(); - config.AuditProcessedMessagesTo("audit"); - config.SendFailedMessagesTo("error"); +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(config); +var host = builder.Build(); +var messageSession = host.Services.GetRequiredService(); +await host.StartAsync(); - var transport = config.UseTransport(); - var routing = transport.Routing(); - var endpoint = await config.StartWithDefaultRoutes(routing); +Console.WriteLine("Started."); +Console.WriteLine("Press 'S' to start a new process or [Enter] to exit."); - Console.WriteLine("Started."); - Console.WriteLine("Press 'S' to start a new process or [Enter] to exit."); +await RunInputLoop(messageSession); - while (true) +await host.StopAsync(); + +static async Task RunInputLoop(IMessageSession messageSession) +{ + while (true) + { + var pressedKey = Console.ReadKey(); + switch (pressedKey.Key) { - var pressedKey = Console.ReadKey(); - switch (pressedKey.Key) + case ConsoleKey.Enter: { - case ConsoleKey.Enter: - { - return; - } - case ConsoleKey.S: - { - await StartSaga(endpoint); - break; - } + return; + } + case ConsoleKey.S: + { + await StartSaga(messageSession); + break; } } } +} - static async Task StartSaga(IMessageSession session) - { - var id = Guid.NewGuid(); - var count = Random.Shared.Next(500, 1000); +static async Task StartSaga(IMessageSession session) +{ + var id = Guid.NewGuid(); + var count = Random.Shared.Next(500, 1000); - await session.SendLocal(new StartProcessing - { - ProcessId = id, - WorkCount = count - }); - Console.WriteLine($"Started process '{id}' with '{count}' work orders."); - } + await session.SendLocal(new StartProcessing + { + ProcessId = id, + WorkCount = count + }); + Console.WriteLine($"Started process '{id}' with '{count}' work orders."); } \ No newline at end of file diff --git a/samples/saga/batching/Core_10/WorkProcessor/Program.cs b/samples/saga/batching/Core_10/WorkProcessor/Program.cs index 479236951e7..e7273346a89 100644 --- a/samples/saga/batching/Core_10/WorkProcessor/Program.cs +++ b/samples/saga/batching/Core_10/WorkProcessor/Program.cs @@ -1,38 +1,19 @@ -using System; -using System.Threading.Tasks; +using Microsoft.Extensions.Hosting; using NServiceBus; -public static class Program -{ - public static async Task Main() - { - var config = new EndpointConfiguration(EndpointNames.WorkProcessor); +var config = new EndpointConfiguration(EndpointNames.WorkProcessor); - config.UsePersistence(); - config.UseTransport(); - //config.UseSerialization(); - config.UseSerialization(); - config.AuditProcessedMessagesTo("audit"); - config.SendFailedMessagesTo("error"); - config.LimitMessageProcessingConcurrencyTo(64); +config.UsePersistence(); +config.UseTransport(); +config.UseSerialization(); +config.AuditProcessedMessagesTo("audit"); +config.SendFailedMessagesTo("error"); +config.LimitMessageProcessingConcurrencyTo(64); - var transport = config.UseTransport(); - var routing = transport.Routing(); - var _ = await config.StartWithDefaultRoutes(routing); +var transport = config.UseTransport(); +var routing = transport.Routing(); +RoutingHelper.ApplyDefaultRouting(routing); - Console.WriteLine("Started."); - Console.WriteLine("Press [Enter] to exit."); - - while (true) - { - var pressedKey = Console.ReadKey(); - switch (pressedKey.Key) - { - case ConsoleKey.Enter: - { - return; - } - } - } - } -} \ No newline at end of file +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(config); +await builder.Build().RunAsync(); \ No newline at end of file diff --git a/samples/scheduling/hangfire/Core_10/Receiver/Program.cs b/samples/scheduling/hangfire/Core_10/Receiver/Program.cs index 34ec497e7b0..b00fa7acbab 100644 --- a/samples/scheduling/hangfire/Core_10/Receiver/Program.cs +++ b/samples/scheduling/hangfire/Core_10/Receiver/Program.cs @@ -1,5 +1,7 @@ using System; using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NServiceBus; class Program @@ -11,10 +13,14 @@ static async Task Main() endpointConfiguration.UseTransport(new LearningTransport()); endpointConfiguration.UseSerialization(); - var endpointInstance = await Endpoint.Start(endpointConfiguration); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + await host.StartAsync(); + Console.WriteLine("Press any key to exit"); Console.WriteLine("Waiting for messages from the Scheduler"); Console.ReadKey(); - await endpointInstance.Stop(); + await host.StopAsync(); } } \ No newline at end of file diff --git a/samples/scheduling/hangfire/Core_10/Scheduler/EndpointHelper.cs b/samples/scheduling/hangfire/Core_10/Scheduler/EndpointHelper.cs index 555a149689e..c24448ff8c4 100644 --- a/samples/scheduling/hangfire/Core_10/Scheduler/EndpointHelper.cs +++ b/samples/scheduling/hangfire/Core_10/Scheduler/EndpointHelper.cs @@ -4,7 +4,7 @@ public static class EndpointHelper { - public static IEndpointInstance Instance { get; set; } + public static IMessageSession MessageSession { get; set; } } #endregion \ No newline at end of file diff --git a/samples/scheduling/hangfire/Core_10/Scheduler/Program.cs b/samples/scheduling/hangfire/Core_10/Scheduler/Program.cs index f5e9028ff15..1136cccbbf0 100644 --- a/samples/scheduling/hangfire/Core_10/Scheduler/Program.cs +++ b/samples/scheduling/hangfire/Core_10/Scheduler/Program.cs @@ -2,6 +2,8 @@ using System.Threading.Tasks; using Hangfire; using Hangfire.MemoryStorage; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NServiceBus; class Program @@ -15,10 +17,14 @@ static async Task Main() #region Configuration - var endpointInstance = await Endpoint.Start(endpointConfiguration); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + var messageSession = host.Services.GetRequiredService(); + await host.StartAsync(); // store the endpointInstance in a static helper class - EndpointHelper.Instance = endpointInstance; + EndpointHelper.MessageSession = messageSession; // use in memory storage. Production should use more robust alternatives: // SqlServer, Redis etc @@ -44,7 +50,7 @@ static async Task Main() #region shutdown scheduler.Dispose(); - await endpointInstance.Stop(); + await host.StopAsync(); #endregion } diff --git a/samples/scheduling/hangfire/Core_10/Scheduler/SendMessageJob.cs b/samples/scheduling/hangfire/Core_10/Scheduler/SendMessageJob.cs index 19466b613d6..41d7baa5915 100644 --- a/samples/scheduling/hangfire/Core_10/Scheduler/SendMessageJob.cs +++ b/samples/scheduling/hangfire/Core_10/Scheduler/SendMessageJob.cs @@ -6,8 +6,8 @@ public static class SendMessageJob { public static Task Run() { - var endpoint = EndpointHelper.Instance; - return endpoint.Send("Samples.HangfireScheduler.Receiver", new MyMessage()); + var messageSession = EndpointHelper.MessageSession; + return messageSession.Send("Samples.HangfireScheduler.Receiver", new MyMessage()); } } #endregion \ No newline at end of file diff --git a/samples/scheduling/hangfire/Core_10/Shared/Shared.csproj b/samples/scheduling/hangfire/Core_10/Shared/Shared.csproj index a2f224dbcc9..c30a9c9d8aa 100644 --- a/samples/scheduling/hangfire/Core_10/Shared/Shared.csproj +++ b/samples/scheduling/hangfire/Core_10/Shared/Shared.csproj @@ -4,6 +4,6 @@ 14.0 - + \ No newline at end of file diff --git a/samples/scheduling/quartz/Core_10/Receiver/Program.cs b/samples/scheduling/quartz/Core_10/Receiver/Program.cs index d5ff87501b6..94a44a23903 100644 --- a/samples/scheduling/quartz/Core_10/Receiver/Program.cs +++ b/samples/scheduling/quartz/Core_10/Receiver/Program.cs @@ -14,5 +14,5 @@ Console.WriteLine("Waiting for messages from the Sender"); Console.WriteLine("Starting..."); -builder.UseNServiceBus(endpointConfiguration); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); await builder.Build().RunAsync(); diff --git a/samples/scheduling/quartz/Core_10/Receiver/Receiver.csproj b/samples/scheduling/quartz/Core_10/Receiver/Receiver.csproj index 9e08818dd1e..b47eec00209 100644 --- a/samples/scheduling/quartz/Core_10/Receiver/Receiver.csproj +++ b/samples/scheduling/quartz/Core_10/Receiver/Receiver.csproj @@ -4,9 +4,6 @@ Exe 14.0 - - - diff --git a/samples/scheduling/quartz/Core_10/Scheduler/Program.cs b/samples/scheduling/quartz/Core_10/Scheduler/Program.cs index 503459c0e04..54cd8ef1433 100644 --- a/samples/scheduling/quartz/Core_10/Scheduler/Program.cs +++ b/samples/scheduling/quartz/Core_10/Scheduler/Program.cs @@ -1,5 +1,7 @@ using System; using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NServiceBus; using Quartz; using Quartz.Impl; @@ -16,7 +18,11 @@ static async Task Main() #region Configuration - var endpointInstance = await Endpoint.Start(endpointConfiguration); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddNServiceBusEndpoint(endpointConfiguration); + var host = builder.Build(); + var messageSession = host.Services.GetRequiredService(); + await host.StartAsync(); LogProvider.SetCurrentLogProvider(new QuartzConsoleLogProvider()); @@ -24,8 +30,8 @@ static async Task Main() var scheduler = await schedulerFactory.GetScheduler(); - // inject the endpointInstance into the scheduler context - scheduler.SetEndpointInstance(endpointInstance); + // inject the messageSession into the scheduler context + scheduler.SetMessageSession(messageSession); await scheduler.Start(); #endregion @@ -61,7 +67,7 @@ static async Task Main() #region shutdown await scheduler.Shutdown(); - await endpointInstance.Stop(); + await host.StopAsync(); #endregion } diff --git a/samples/scheduling/quartz/Core_10/Scheduler/QuartzContextExtensions.cs b/samples/scheduling/quartz/Core_10/Scheduler/QuartzContextExtensions.cs index 892aee50c3c..00966e9ecd6 100644 --- a/samples/scheduling/quartz/Core_10/Scheduler/QuartzContextExtensions.cs +++ b/samples/scheduling/quartz/Core_10/Scheduler/QuartzContextExtensions.cs @@ -5,14 +5,14 @@ public static class QuartzContextExtensions { - public static IEndpointInstance EndpointInstance(this IJobExecutionContext context) + public static IMessageSession MessageSession(this IJobExecutionContext context) { - return (IEndpointInstance) context.Scheduler.Context["EndpointInstance"]; + return (IMessageSession) context.Scheduler.Context["MessageSession"]; } - public static void SetEndpointInstance(this IScheduler scheduler, IEndpointInstance instance) + public static void SetMessageSession(this IScheduler scheduler, IMessageSession messageSession) { - scheduler.Context["EndpointInstance"] = instance; + scheduler.Context["MessageSession"] = messageSession; } } diff --git a/samples/scheduling/quartz/Core_10/Scheduler/SendMessageJob.cs b/samples/scheduling/quartz/Core_10/Scheduler/SendMessageJob.cs index ca06a4a2683..39f55cf92f8 100644 --- a/samples/scheduling/quartz/Core_10/Scheduler/SendMessageJob.cs +++ b/samples/scheduling/quartz/Core_10/Scheduler/SendMessageJob.cs @@ -12,9 +12,9 @@ public async Task Execute(IJobExecutionContext context) { try { - var endpointInstance = context.EndpointInstance(); + var messageSession = context.MessageSession(); var message = new MyMessage(); - await endpointInstance.Send("Samples.QuartzScheduler.Receiver", message); + await messageSession.Send("Samples.QuartzScheduler.Receiver", message); } catch (Exception exception) { diff --git a/samples/scheduling/quartz/Core_10/Shared/Shared.csproj b/samples/scheduling/quartz/Core_10/Shared/Shared.csproj index a2f224dbcc9..c30a9c9d8aa 100644 --- a/samples/scheduling/quartz/Core_10/Shared/Shared.csproj +++ b/samples/scheduling/quartz/Core_10/Shared/Shared.csproj @@ -4,6 +4,6 @@ 14.0 - + \ No newline at end of file diff --git a/samples/servicecontrol/fix-messages/Core_10/MessageRepairingEndpoint/MessageRepairingEndpoint.csproj b/samples/servicecontrol/fix-messages/Core_10/MessageRepairingEndpoint/MessageRepairingEndpoint.csproj index 1c9aa5a1f80..50585add435 100644 --- a/samples/servicecontrol/fix-messages/Core_10/MessageRepairingEndpoint/MessageRepairingEndpoint.csproj +++ b/samples/servicecontrol/fix-messages/Core_10/MessageRepairingEndpoint/MessageRepairingEndpoint.csproj @@ -10,8 +10,4 @@ - - - - \ No newline at end of file diff --git a/samples/servicecontrol/fix-messages/Core_10/MessageRepairingEndpoint/Program.cs b/samples/servicecontrol/fix-messages/Core_10/MessageRepairingEndpoint/Program.cs index 4b05021b975..2c1c666edfe 100644 --- a/samples/servicecontrol/fix-messages/Core_10/MessageRepairingEndpoint/Program.cs +++ b/samples/servicecontrol/fix-messages/Core_10/MessageRepairingEndpoint/Program.cs @@ -8,6 +8,6 @@ endpointConfiguration.UseSerialization(); endpointConfiguration.UseTransport(); -builder.UseNServiceBus(endpointConfiguration); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); await builder.Build().RunAsync(); \ No newline at end of file diff --git a/samples/servicecontrol/fix-messages/Core_10/Receiver/Program.cs b/samples/servicecontrol/fix-messages/Core_10/Receiver/Program.cs index 5a54b047d39..3653c3b992b 100644 --- a/samples/servicecontrol/fix-messages/Core_10/Receiver/Program.cs +++ b/samples/servicecontrol/fix-messages/Core_10/Receiver/Program.cs @@ -26,6 +26,6 @@ #endregion -builder.UseNServiceBus(endpointConfiguration); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); await builder.Build().RunAsync(); \ No newline at end of file diff --git a/samples/servicecontrol/fix-messages/Core_10/Receiver/Receiver.csproj b/samples/servicecontrol/fix-messages/Core_10/Receiver/Receiver.csproj index 9d3ee663613..03f8354ff59 100644 --- a/samples/servicecontrol/fix-messages/Core_10/Receiver/Receiver.csproj +++ b/samples/servicecontrol/fix-messages/Core_10/Receiver/Receiver.csproj @@ -10,8 +10,4 @@ - - - - \ No newline at end of file diff --git a/samples/servicecontrol/fix-messages/Core_10/Sender/Program.cs b/samples/servicecontrol/fix-messages/Core_10/Sender/Program.cs index 2987d46d22b..9a23f5e0dac 100644 --- a/samples/servicecontrol/fix-messages/Core_10/Sender/Program.cs +++ b/samples/servicecontrol/fix-messages/Core_10/Sender/Program.cs @@ -1,4 +1,6 @@ using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NServiceBus; Console.Title = "Sender"; @@ -7,7 +9,11 @@ var routing = endpointConfiguration.UseTransport().Routing(); routing.RouteToEndpoint(typeof(SimpleMessage), "FixMalformedMessages.Receiver"); -var endpointInstance = await Endpoint.Start(endpointConfiguration); +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +var host = builder.Build(); +var messageSession = host.Services.GetRequiredService(); +await host.StartAsync(); Console.WriteLine("Press 'Enter' to send a new message. Press any other key to finish."); @@ -27,11 +33,11 @@ Id = guid.ToString().ToLowerInvariant() }; - await endpointInstance.Send(simpleMessage); + await messageSession.Send(simpleMessage); Console.WriteLine($"Sent a new message with Id = {guid}."); Console.WriteLine("Press 'Enter' to send a new message. Press any other key to finish."); } -await endpointInstance.Stop(); \ No newline at end of file +await host.StopAsync(); \ No newline at end of file diff --git a/samples/servicecontrol/fix-messages/Core_10/Shared/Shared.csproj b/samples/servicecontrol/fix-messages/Core_10/Shared/Shared.csproj index afb41271b56..5bf55bdca71 100644 --- a/samples/servicecontrol/fix-messages/Core_10/Shared/Shared.csproj +++ b/samples/servicecontrol/fix-messages/Core_10/Shared/Shared.csproj @@ -6,7 +6,7 @@ - + \ No newline at end of file diff --git a/samples/sql-persistence/injecting-services/SqlPersistence_9/Endpoint/Endpoint.csproj b/samples/sql-persistence/injecting-services/SqlPersistence_9/Endpoint/Endpoint.csproj index a889914583c..746f5780df0 100644 --- a/samples/sql-persistence/injecting-services/SqlPersistence_9/Endpoint/Endpoint.csproj +++ b/samples/sql-persistence/injecting-services/SqlPersistence_9/Endpoint/Endpoint.csproj @@ -9,8 +9,7 @@ - - + diff --git a/samples/sql-persistence/injecting-services/SqlPersistence_9/Endpoint/Program.cs b/samples/sql-persistence/injecting-services/SqlPersistence_9/Endpoint/Program.cs index 19e8bdd9b7e..54bfdc5b6b1 100644 --- a/samples/sql-persistence/injecting-services/SqlPersistence_9/Endpoint/Program.cs +++ b/samples/sql-persistence/injecting-services/SqlPersistence_9/Endpoint/Program.cs @@ -40,21 +40,19 @@ #endregion +// Ensure the database exists before starting the endpoint +SqlHelper.EnsureDatabaseExists(connectionString); + +var builder = Host.CreateApplicationBuilder(args); + #region DependencyInjectionConfig -endpointConfiguration.RegisterComponents(services => -{ - services.AddScoped(); - services.AddScoped(); -}); +builder.Services.AddScoped(); +builder.Services.AddScoped(); #endregion -// Ensure the database exists before starting the endpoint -SqlHelper.EnsureDatabaseExists(connectionString); - -var builder = Host.CreateApplicationBuilder(args); -builder.UseNServiceBus(endpointConfiguration); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); var host = builder.Build(); diff --git a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointMySql/Program.cs b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointMySql/Program.cs index 5adbd5cecce..4ef09346ec6 100644 --- a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointMySql/Program.cs +++ b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointMySql/Program.cs @@ -1,42 +1,40 @@ using System; -using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using MySql.Data.MySqlClient; using NServiceBus; -partial class Program -{ - static async Task Main() - { - Console.Title = "EndpointMySql"; +Console.Title = "EndpointMySql"; - var endpointConfiguration = new EndpointConfiguration("EndpointMySql"); - endpointConfiguration.UseSerialization(); +var endpointConfiguration = new EndpointConfiguration("EndpointMySql"); +endpointConfiguration.UseSerialization(); - endpointConfiguration.UseTransport(new LearningTransport()); - endpointConfiguration.EnableInstallers(); +endpointConfiguration.UseTransport(new LearningTransport()); +endpointConfiguration.EnableInstallers(); - var persistence = endpointConfiguration.UsePersistence(); +var persistence = endpointConfiguration.UsePersistence(); - var connection = "server=localhost;user=root;database=sqlpersistencesampletransition;port=3306;password=yourStrong(!)Password;AllowUserVariables=True;AutoEnlist=false"; +var connection = "server=localhost;user=root;database=sqlpersistencesampletransition;port=3306;password=yourStrong(!)Password;AllowUserVariables=True;AutoEnlist=false"; - persistence.SqlDialect(); - persistence.ConnectionBuilder( - () => new MySqlConnection(connection)); +persistence.SqlDialect(); +persistence.ConnectionBuilder( + () => new MySqlConnection(connection)); - var subscriptions = persistence.SubscriptionSettings(); - subscriptions.CacheFor(TimeSpan.FromMinutes(1)); +var subscriptions = persistence.SubscriptionSettings(); +subscriptions.CacheFor(TimeSpan.FromMinutes(1)); - SqlHelper.EnsureDatabaseExists(connection); +SqlHelper.EnsureDatabaseExists(connection); - var endpointInstance = await Endpoint.Start(endpointConfiguration); +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +var host = builder.Build(); +var messageSession = host.Services.GetRequiredService(); +await host.StartAsync(); +await SendMessage(messageSession); - await SendMessage(endpointInstance); +Console.WriteLine("StartOrder Message sent"); - Console.WriteLine("StartOrder Message sent"); +Console.WriteLine("Press any key to exit"); +Console.ReadKey(); - Console.WriteLine("Press any key to exit"); - Console.ReadKey(); - - await endpointInstance.Stop(); - } -} \ No newline at end of file +await host.StopAsync(); \ No newline at end of file diff --git a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointMySql/SendMessage.cs b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointMySql/SendMessage.cs index 1faa78288ca..b1f3bd26337 100644 --- a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointMySql/SendMessage.cs +++ b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointMySql/SendMessage.cs @@ -3,12 +3,12 @@ partial class Program { - static Task SendMessage(IEndpointInstance endpointInstance) + static Task SendMessage(IMessageSession messageSession) { var message = new StartOrder { OrderNumber = 10 }; - return endpointInstance.SendLocal(message); + return messageSession.SendLocal(message); } } \ No newline at end of file diff --git a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointOracle/Program.cs b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointOracle/Program.cs index 1fd2dc72cdf..d4b5b046627 100644 --- a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointOracle/Program.cs +++ b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointOracle/Program.cs @@ -1,39 +1,37 @@ using System; -using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NServiceBus; using Oracle.ManagedDataAccess.Client; -partial class Program -{ - static async Task Main() - { - Console.Title = "EndpointOracle"; +Console.Title = "EndpointOracle"; - var endpointConfiguration = new EndpointConfiguration("EndpointOracle"); +var endpointConfiguration = new EndpointConfiguration("EndpointOracle"); - endpointConfiguration.UseSerialization(); - endpointConfiguration.UseTransport(new LearningTransport()); - endpointConfiguration.EnableInstallers(); +endpointConfiguration.UseSerialization(); +endpointConfiguration.UseTransport(new LearningTransport()); +endpointConfiguration.EnableInstallers(); - var persistence = endpointConfiguration.UsePersistence(); +var persistence = endpointConfiguration.UsePersistence(); - var connection = "Data Source=localhost;User Id=SYSTEM; Password=yourStrong(!)Password; Enlist=false"; +var connection = "Data Source=localhost;User Id=SYSTEM; Password=yourStrong(!)Password; Enlist=false"; - persistence.SqlDialect(); - persistence.ConnectionBuilder(() => new OracleConnection(connection)); +persistence.SqlDialect(); +persistence.ConnectionBuilder(() => new OracleConnection(connection)); - var subscriptions = persistence.SubscriptionSettings(); - subscriptions.CacheFor(TimeSpan.FromMinutes(1)); +var subscriptions = persistence.SubscriptionSettings(); +subscriptions.CacheFor(TimeSpan.FromMinutes(1)); - var endpointInstance = await Endpoint.Start(endpointConfiguration); +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +var host = builder.Build(); +var messageSession = host.Services.GetRequiredService(); +await host.StartAsync(); +await SendMessage(messageSession); - await SendMessage(endpointInstance); +Console.WriteLine("StartOrder Message sent"); - Console.WriteLine("StartOrder Message sent"); +Console.WriteLine("Press any key to exit"); +Console.ReadKey(); - Console.WriteLine("Press any key to exit"); - Console.ReadKey(); - - await endpointInstance.Stop(); - } -} +await host.StopAsync(); \ No newline at end of file diff --git a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointOracle/SendMessage.cs b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointOracle/SendMessage.cs index 1faa78288ca..b1f3bd26337 100644 --- a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointOracle/SendMessage.cs +++ b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointOracle/SendMessage.cs @@ -3,12 +3,12 @@ partial class Program { - static Task SendMessage(IEndpointInstance endpointInstance) + static Task SendMessage(IMessageSession messageSession) { var message = new StartOrder { OrderNumber = 10 }; - return endpointInstance.SendLocal(message); + return messageSession.SendLocal(message); } } \ No newline at end of file diff --git a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointPostgreSql/Program.cs b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointPostgreSql/Program.cs index bfa2697337f..3642b9f49ee 100644 --- a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointPostgreSql/Program.cs +++ b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointPostgreSql/Program.cs @@ -1,51 +1,49 @@ using System; -using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Npgsql; using NpgsqlTypes; using NServiceBus; -partial class Program -{ - static async Task Main() - { - Console.Title = "EndpointPostgreSql"; - - var endpointConfiguration = new EndpointConfiguration("EndpointPostgreSql"); +Console.Title = "EndpointPostgreSql"; - endpointConfiguration.UseSerialization(); - endpointConfiguration.UseTransport(new LearningTransport()); - endpointConfiguration.EnableInstallers(); +var endpointConfiguration = new EndpointConfiguration("EndpointPostgreSql"); - var connection = "Host=localhost;Username=postgres;Password=yourStrong(!)Password;Database=NsbSamplesSqlPersistenceTransition"; +endpointConfiguration.UseSerialization(); +endpointConfiguration.UseTransport(new LearningTransport()); +endpointConfiguration.EnableInstallers(); - var persistence = endpointConfiguration.UsePersistence(); +var connection = "Host=localhost;Username=postgres;Password=yourStrong(!)Password;Database=NsbSamplesSqlPersistenceTransition"; - var dialect = persistence.SqlDialect(); +var persistence = endpointConfiguration.UsePersistence(); - dialect.JsonBParameterModifier( - modifier: parameter => - { - var npgsqlParameter = (NpgsqlParameter)parameter; - npgsqlParameter.NpgsqlDbType = NpgsqlDbType.Jsonb; - }); +var dialect = persistence.SqlDialect(); - persistence.ConnectionBuilder( - () => new NpgsqlConnection(connection)); +dialect.JsonBParameterModifier( + modifier: parameter => + { + var npgsqlParameter = (NpgsqlParameter)parameter; + npgsqlParameter.NpgsqlDbType = NpgsqlDbType.Jsonb; + }); - var subscriptions = persistence.SubscriptionSettings(); - subscriptions.CacheFor(TimeSpan.FromMinutes(1)); +persistence.ConnectionBuilder( + () => new NpgsqlConnection(connection)); - SqlHelper.EnsureDatabaseExists(connection); +var subscriptions = persistence.SubscriptionSettings(); +subscriptions.CacheFor(TimeSpan.FromMinutes(1)); - var endpointInstance = await Endpoint.Start(endpointConfiguration); +SqlHelper.EnsureDatabaseExists(connection); - await SendMessage(endpointInstance); +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +var host = builder.Build(); +var messageSession = host.Services.GetRequiredService(); +await host.StartAsync(); +await SendMessage(messageSession); - Console.WriteLine("StartOrder Message sent"); +Console.WriteLine("StartOrder Message sent"); - Console.WriteLine("Press any key to exit"); - Console.ReadKey(); +Console.WriteLine("Press any key to exit"); +Console.ReadKey(); - await endpointInstance.Stop(); - } -} \ No newline at end of file +await host.StopAsync(); \ No newline at end of file diff --git a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointPostgreSql/SendMessage.cs b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointPostgreSql/SendMessage.cs index 1faa78288ca..b1f3bd26337 100644 --- a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointPostgreSql/SendMessage.cs +++ b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointPostgreSql/SendMessage.cs @@ -3,12 +3,12 @@ partial class Program { - static Task SendMessage(IEndpointInstance endpointInstance) + static Task SendMessage(IMessageSession messageSession) { var message = new StartOrder { OrderNumber = 10 }; - return endpointInstance.SendLocal(message); + return messageSession.SendLocal(message); } } \ No newline at end of file diff --git a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointSqlServer/Program.cs b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointSqlServer/Program.cs index 8f3b1b3badf..ff19c57d556 100644 --- a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointSqlServer/Program.cs +++ b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointSqlServer/Program.cs @@ -1,42 +1,41 @@ using System; using Microsoft.Data.SqlClient; -using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using NServiceBus; -partial class Program -{ - static async Task Main() - { - Console.Title = "EndpointSqlServer"; +Console.Title = "EndpointSqlServer"; - var endpointConfiguration = new EndpointConfiguration("EndpointSqlServer"); +var endpointConfiguration = new EndpointConfiguration("EndpointSqlServer"); - endpointConfiguration.UseSerialization(); - endpointConfiguration.UseTransport(new LearningTransport()); - endpointConfiguration.EnableInstallers(); +endpointConfiguration.UseSerialization(); +endpointConfiguration.UseTransport(new LearningTransport()); +endpointConfiguration.EnableInstallers(); - // for SqlExpress use Data Source=.\SqlExpress;Initial Catalog=NsbSamplesSqlPersistenceTransition;Integrated Security=True;Encrypt=false - //var connectionString = "Server=localhost,1433;Initial Catalog=NsbSamplesSqlPersistenceTransition;User Id=SA;Password=yourStrong(!)Password;Encrypt=false"; - // for LocalDB: - var connectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=NsbSamplesSqlPersistenceTransition;Integrated Security=True;Connect Timeout=30;Encrypt=False;Trust Server Certificate=False;Application Intent=ReadWrite;Multi Subnet Failover=False"; +// for SqlExpress use Data Source=.\SqlExpress;Initial Catalog=NsbSamplesSqlPersistenceTransition;Integrated Security=True;Encrypt=false +//var connectionString = "Server=localhost,1433;Initial Catalog=NsbSamplesSqlPersistenceTransition;User Id=SA;Password=yourStrong(!)Password;Encrypt=false"; +// for LocalDB: +var connectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=NsbSamplesSqlPersistenceTransition;Integrated Security=True;Connect Timeout=30;Encrypt=False;Trust Server Certificate=False;Application Intent=ReadWrite;Multi Subnet Failover=False"; - var persistence = endpointConfiguration.UsePersistence(); - persistence.SqlDialect(); - persistence.ConnectionBuilder( - () => new SqlConnection(connectionString)); +var persistence = endpointConfiguration.UsePersistence(); +persistence.SqlDialect(); +persistence.ConnectionBuilder( + () => new SqlConnection(connectionString)); - var subscriptions = persistence.SubscriptionSettings(); - subscriptions.CacheFor(TimeSpan.FromMinutes(1)); +var subscriptions = persistence.SubscriptionSettings(); +subscriptions.CacheFor(TimeSpan.FromMinutes(1)); - SqlHelper.EnsureDatabaseExists(connectionString); +SqlHelper.EnsureDatabaseExists(connectionString); - var endpointInstance = await Endpoint.Start(endpointConfiguration); - await SendMessage(endpointInstance); +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +var host = builder.Build(); +var messageSession = host.Services.GetRequiredService(); +await host.StartAsync(); +await SendMessage(messageSession); - Console.WriteLine("StartOrder Message sent"); - Console.WriteLine("Press any key to exit"); - Console.ReadKey(); +Console.WriteLine("StartOrder Message sent"); +Console.WriteLine("Press any key to exit"); +Console.ReadKey(); - await endpointInstance.Stop(); - } -} \ No newline at end of file +await host.StopAsync(); \ No newline at end of file diff --git a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointSqlServer/SendMessage.cs b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointSqlServer/SendMessage.cs index 1faa78288ca..b1f3bd26337 100644 --- a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointSqlServer/SendMessage.cs +++ b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/EndpointSqlServer/SendMessage.cs @@ -3,12 +3,12 @@ partial class Program { - static Task SendMessage(IEndpointInstance endpointInstance) + static Task SendMessage(IMessageSession messageSession) { var message = new StartOrder { OrderNumber = 10 }; - return endpointInstance.SendLocal(message); + return messageSession.SendLocal(message); } } \ No newline at end of file diff --git a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/Shared/SharedPhase1.csproj b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/Shared/SharedPhase1.csproj index ee87195cfee..aa0cc4ae405 100644 --- a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/Shared/SharedPhase1.csproj +++ b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase1/Shared/SharedPhase1.csproj @@ -7,7 +7,7 @@ - + diff --git a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase2/EndpointMySql/SendMessage.cs b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase2/EndpointMySql/SendMessage.cs index 25d3c119b7d..08f16dfa841 100644 --- a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase2/EndpointMySql/SendMessage.cs +++ b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase2/EndpointMySql/SendMessage.cs @@ -4,13 +4,13 @@ partial class Program { - static Task SendMessage(IEndpointInstance endpointInstance) + static Task SendMessage(IMessageSession messageSession) { var message = new StartOrder { OrderNumber = 10, OrderId = new Guid("0f8fad5b-d9cb-469f-a165-70867728950e") }; - return endpointInstance.SendLocal(message); + return messageSession.SendLocal(message); } } \ No newline at end of file diff --git a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase2/EndpointOracle/SendMessage.cs b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase2/EndpointOracle/SendMessage.cs index 25d3c119b7d..08f16dfa841 100644 --- a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase2/EndpointOracle/SendMessage.cs +++ b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase2/EndpointOracle/SendMessage.cs @@ -4,13 +4,13 @@ partial class Program { - static Task SendMessage(IEndpointInstance endpointInstance) + static Task SendMessage(IMessageSession messageSession) { var message = new StartOrder { OrderNumber = 10, OrderId = new Guid("0f8fad5b-d9cb-469f-a165-70867728950e") }; - return endpointInstance.SendLocal(message); + return messageSession.SendLocal(message); } } \ No newline at end of file diff --git a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase2/EndpointPostgreSql/SendMessage.cs b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase2/EndpointPostgreSql/SendMessage.cs index 25d3c119b7d..08f16dfa841 100644 --- a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase2/EndpointPostgreSql/SendMessage.cs +++ b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase2/EndpointPostgreSql/SendMessage.cs @@ -4,13 +4,13 @@ partial class Program { - static Task SendMessage(IEndpointInstance endpointInstance) + static Task SendMessage(IMessageSession messageSession) { var message = new StartOrder { OrderNumber = 10, OrderId = new Guid("0f8fad5b-d9cb-469f-a165-70867728950e") }; - return endpointInstance.SendLocal(message); + return messageSession.SendLocal(message); } } \ No newline at end of file diff --git a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase2/EndpointSqlServer/SendMessage.cs b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase2/EndpointSqlServer/SendMessage.cs index 25d3c119b7d..08f16dfa841 100644 --- a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase2/EndpointSqlServer/SendMessage.cs +++ b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase2/EndpointSqlServer/SendMessage.cs @@ -4,13 +4,13 @@ partial class Program { - static Task SendMessage(IEndpointInstance endpointInstance) + static Task SendMessage(IMessageSession messageSession) { var message = new StartOrder { OrderNumber = 10, OrderId = new Guid("0f8fad5b-d9cb-469f-a165-70867728950e") }; - return endpointInstance.SendLocal(message); + return messageSession.SendLocal(message); } } \ No newline at end of file diff --git a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase2/Shared/SharedPhase2.csproj b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase2/Shared/SharedPhase2.csproj index ee87195cfee..aa0cc4ae405 100644 --- a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase2/Shared/SharedPhase2.csproj +++ b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase2/Shared/SharedPhase2.csproj @@ -7,7 +7,7 @@ - + diff --git a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase3/EndpointMySql/SendMessage.cs b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase3/EndpointMySql/SendMessage.cs index 465b8519488..56855cf9618 100644 --- a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase3/EndpointMySql/SendMessage.cs +++ b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase3/EndpointMySql/SendMessage.cs @@ -4,12 +4,12 @@ partial class Program { - static Task SendMessage(IEndpointInstance endpointInstance) + static Task SendMessage(IMessageSession messageSession) { var message = new StartOrder { OrderId = new Guid("0f8fad5b-d9cb-469f-a165-70867728950e") }; - return endpointInstance.SendLocal(message); + return messageSession.SendLocal(message); } } \ No newline at end of file diff --git a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase3/EndpointOracle/SendMessage.cs b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase3/EndpointOracle/SendMessage.cs index 465b8519488..56855cf9618 100644 --- a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase3/EndpointOracle/SendMessage.cs +++ b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase3/EndpointOracle/SendMessage.cs @@ -4,12 +4,12 @@ partial class Program { - static Task SendMessage(IEndpointInstance endpointInstance) + static Task SendMessage(IMessageSession messageSession) { var message = new StartOrder { OrderId = new Guid("0f8fad5b-d9cb-469f-a165-70867728950e") }; - return endpointInstance.SendLocal(message); + return messageSession.SendLocal(message); } } \ No newline at end of file diff --git a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase3/EndpointPostgreSql/SendMessage.cs b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase3/EndpointPostgreSql/SendMessage.cs index 465b8519488..56855cf9618 100644 --- a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase3/EndpointPostgreSql/SendMessage.cs +++ b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase3/EndpointPostgreSql/SendMessage.cs @@ -4,12 +4,12 @@ partial class Program { - static Task SendMessage(IEndpointInstance endpointInstance) + static Task SendMessage(IMessageSession messageSession) { var message = new StartOrder { OrderId = new Guid("0f8fad5b-d9cb-469f-a165-70867728950e") }; - return endpointInstance.SendLocal(message); + return messageSession.SendLocal(message); } } \ No newline at end of file diff --git a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase3/EndpointSqlServer/SendMessage.cs b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase3/EndpointSqlServer/SendMessage.cs index 465b8519488..56855cf9618 100644 --- a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase3/EndpointSqlServer/SendMessage.cs +++ b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase3/EndpointSqlServer/SendMessage.cs @@ -4,12 +4,12 @@ partial class Program { - static Task SendMessage(IEndpointInstance endpointInstance) + static Task SendMessage(IMessageSession messageSession) { var message = new StartOrder { OrderId = new Guid("0f8fad5b-d9cb-469f-a165-70867728950e") }; - return endpointInstance.SendLocal(message); + return messageSession.SendLocal(message); } } \ No newline at end of file diff --git a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase3/Shared/SharedPhase3.csproj b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase3/Shared/SharedPhase3.csproj index ee87195cfee..aa0cc4ae405 100644 --- a/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase3/Shared/SharedPhase3.csproj +++ b/samples/sql-persistence/transitioning-correlation-ids/SqlPersistence_9/Phase3/Shared/SharedPhase3.csproj @@ -7,7 +7,7 @@ - + diff --git a/samples/startup-shutdown-sequence/Core_10/Sample/ExtensionPoints/MyFeature.cs b/samples/startup-shutdown-sequence/Core_10/Sample/ExtensionPoints/MyFeature.cs deleted file mode 100644 index c418479e1b1..00000000000 --- a/samples/startup-shutdown-sequence/Core_10/Sample/ExtensionPoints/MyFeature.cs +++ /dev/null @@ -1,11 +0,0 @@ -using NServiceBus.Features; - -public class MyFeature : - Feature -{ - protected override void Setup(FeatureConfigurationContext context) - { - Logger.WriteLine("Inside Feature.Setup"); - context.RegisterStartupTask(new MyFeatureStartupTask()); - } -} \ No newline at end of file diff --git a/samples/startup-shutdown-sequence/Core_10/Sample/ExtensionPoints/MyFeatureStartupTask.cs b/samples/startup-shutdown-sequence/Core_10/Sample/ExtensionPoints/MyFeatureStartupTask.cs deleted file mode 100644 index a5fc7b2cb06..00000000000 --- a/samples/startup-shutdown-sequence/Core_10/Sample/ExtensionPoints/MyFeatureStartupTask.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System.Threading; -using System.Threading.Tasks; -using NServiceBus; -using NServiceBus.Features; - -public class MyFeatureStartupTask : - FeatureStartupTask -{ - protected override Task OnStart(IMessageSession session, CancellationToken token) - { - Logger.WriteLine("Inside FeatureStartupTask.OnStart"); - return Task.CompletedTask; - } - - protected override Task OnStop(IMessageSession session, CancellationToken token) - { - Logger.WriteLine("Inside FeatureStartupTask.OnStop"); - return Task.CompletedTask; - } -} \ No newline at end of file diff --git a/samples/startup-shutdown-sequence/Core_10/Sample/ExtensionPoints/NeedInitialization.cs b/samples/startup-shutdown-sequence/Core_10/Sample/ExtensionPoints/NeedInitialization.cs deleted file mode 100644 index ffd1cbe365f..00000000000 --- a/samples/startup-shutdown-sequence/Core_10/Sample/ExtensionPoints/NeedInitialization.cs +++ /dev/null @@ -1,10 +0,0 @@ -using NServiceBus; - -public class NeedInitialization : - INeedInitialization -{ - public void Customize(EndpointConfiguration endpointConfiguration) - { - Logger.WriteLine("Inside INeedInitialization.Customize"); - } -} \ No newline at end of file diff --git a/samples/startup-shutdown-sequence/Core_10/Sample/ExtensionPoints/NeedToInstallSomething.cs b/samples/startup-shutdown-sequence/Core_10/Sample/ExtensionPoints/NeedToInstallSomething.cs deleted file mode 100644 index 73e8e22110e..00000000000 --- a/samples/startup-shutdown-sequence/Core_10/Sample/ExtensionPoints/NeedToInstallSomething.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Threading; -using System.Threading.Tasks; -using NServiceBus.Installation; - -public class NeedToInstallSomething : - INeedToInstallSomething -{ - public Task Install(string identity, CancellationToken token) - { - Logger.WriteLine("Inside INeedToInstallSomething.Install"); - return Task.CompletedTask; - } -} \ No newline at end of file diff --git a/samples/startup-shutdown-sequence/Core_10/Sample/Logger.cs b/samples/startup-shutdown-sequence/Core_10/Sample/Logger.cs deleted file mode 100644 index 286a391e82c..00000000000 --- a/samples/startup-shutdown-sequence/Core_10/Sample/Logger.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.IO; -using System.Threading; -using NServiceBus.Logging; - -#region Logger -static class Logger -{ - static ILog log = LogManager.GetLogger(typeof(Logger)); - public static string OutputFilePath; - static object locker = new object(); - - static Logger() - { - OutputFilePath = Path.GetFullPath("StartupShutdownSequence.txt"); - AppDomain.CurrentDomain.ProcessExit += Exit; - File.Delete(OutputFilePath); - File.AppendAllText(OutputFilePath, "startcode"); - File.AppendAllText(OutputFilePath, " StartupShutdownSequence\r\n"); - } - - static void Exit(object sender, EventArgs e) - { - File.AppendAllText(OutputFilePath, "endcode"); - } - - public static void WriteLine(string message) - { - message = $"Thread:{Thread.CurrentThread.ManagedThreadId} {message}\r\n"; - log.Info(message); - lock (locker) - { - File.AppendAllText(OutputFilePath, message); - } - } - -} -#endregion \ No newline at end of file diff --git a/samples/startup-shutdown-sequence/Core_10/Sample/Program.cs b/samples/startup-shutdown-sequence/Core_10/Sample/Program.cs deleted file mode 100644 index aa399212f85..00000000000 --- a/samples/startup-shutdown-sequence/Core_10/Sample/Program.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; -using System.Threading.Tasks; -using NServiceBus; -using NServiceBus.Logging; - -class Program -{ - static async Task Main() - { - Console.Title = "StartupShutdown"; - LogManager.Use().Level(LogLevel.Error); - #region Program - Logger.WriteLine("Starting configuration"); - var endpointConfiguration = new EndpointConfiguration("Samples.StartupShutdown"); - endpointConfiguration.EnableInstallers(); - endpointConfiguration.EnableFeature(); - endpointConfiguration.UseSerialization(); - endpointConfiguration.UseTransport(new LearningTransport()); - - Logger.WriteLine("Calling Endpoint.Start"); - var endpointInstance = await Endpoint.Start(endpointConfiguration); - // simulate some activity - await Task.Delay(500); - - Logger.WriteLine("Endpoint is processing messages"); - Logger.WriteLine("Calling IEndpointInstance.Stop"); - await endpointInstance.Stop(); - Logger.WriteLine("Finished"); - #endregion - Console.WriteLine($"Logged information to {Logger.OutputFilePath}"); - Console.WriteLine("Press any key to exit"); - Console.ReadKey(); - } -} diff --git a/samples/startup-shutdown-sequence/Core_10/Sample/Sample.csproj b/samples/startup-shutdown-sequence/Core_10/Sample/Sample.csproj deleted file mode 100644 index 41609bc5fcc..00000000000 --- a/samples/startup-shutdown-sequence/Core_10/Sample/Sample.csproj +++ /dev/null @@ -1,10 +0,0 @@ - - - net10.0 - Exe - 14.0 - - - - - \ No newline at end of file diff --git a/samples/startup-shutdown-sequence/Core_10/StartupShutdown.sln b/samples/startup-shutdown-sequence/Core_10/StartupShutdown.sln deleted file mode 100644 index 50055481477..00000000000 --- a/samples/startup-shutdown-sequence/Core_10/StartupShutdown.sln +++ /dev/null @@ -1,19 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29728.190 -MinimumVisualStudioVersion = 15.0.26730.12 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sample", "Sample\Sample.csproj", "{48F718EE-6C45-41BA-80EC-81BF34D4A623}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {48F718EE-6C45-41BA-80EC-81BF34D4A623}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {48F718EE-6C45-41BA-80EC-81BF34D4A623}.Debug|Any CPU.Build.0 = Debug|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/samples/startup-shutdown-sequence/Core_10/StartupShutdownSequence.txt b/samples/startup-shutdown-sequence/Core_10/StartupShutdownSequence.txt deleted file mode 100644 index a139f02287e..00000000000 --- a/samples/startup-shutdown-sequence/Core_10/StartupShutdownSequence.txt +++ /dev/null @@ -1,13 +0,0 @@ -startcode StartupShutdownSequence -Thread:1 Starting configuration -Thread:1 Calling Endpoint.Start -Thread:1 Inside INeedInitialization.Customize -Thread:1 Inside WantToRunBeforeConfigurationIsFinalized.Run -Thread:1 Inside Feature.Setup -Thread:1 Inside INeedToInstallSomething.Install -Thread:1 Inside FeatureStartupTask.OnStart -Thread:11 Endpoint is processing messages -Thread:11 Calling IEndpointInstance.Stop -Thread:7 Inside FeatureStartupTask.OnStop -Thread:7 Finished -endcode \ No newline at end of file diff --git a/samples/startup-shutdown-sequence/Core_9/Sample/ExtensionPoints/MyFeature.cs b/samples/startup-shutdown-sequence/Core_9/Sample/ExtensionPoints/MyFeature.cs deleted file mode 100644 index c418479e1b1..00000000000 --- a/samples/startup-shutdown-sequence/Core_9/Sample/ExtensionPoints/MyFeature.cs +++ /dev/null @@ -1,11 +0,0 @@ -using NServiceBus.Features; - -public class MyFeature : - Feature -{ - protected override void Setup(FeatureConfigurationContext context) - { - Logger.WriteLine("Inside Feature.Setup"); - context.RegisterStartupTask(new MyFeatureStartupTask()); - } -} \ No newline at end of file diff --git a/samples/startup-shutdown-sequence/Core_9/Sample/ExtensionPoints/MyFeatureStartupTask.cs b/samples/startup-shutdown-sequence/Core_9/Sample/ExtensionPoints/MyFeatureStartupTask.cs deleted file mode 100644 index a5fc7b2cb06..00000000000 --- a/samples/startup-shutdown-sequence/Core_9/Sample/ExtensionPoints/MyFeatureStartupTask.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System.Threading; -using System.Threading.Tasks; -using NServiceBus; -using NServiceBus.Features; - -public class MyFeatureStartupTask : - FeatureStartupTask -{ - protected override Task OnStart(IMessageSession session, CancellationToken token) - { - Logger.WriteLine("Inside FeatureStartupTask.OnStart"); - return Task.CompletedTask; - } - - protected override Task OnStop(IMessageSession session, CancellationToken token) - { - Logger.WriteLine("Inside FeatureStartupTask.OnStop"); - return Task.CompletedTask; - } -} \ No newline at end of file diff --git a/samples/startup-shutdown-sequence/Core_9/Sample/ExtensionPoints/NeedInitialization.cs b/samples/startup-shutdown-sequence/Core_9/Sample/ExtensionPoints/NeedInitialization.cs deleted file mode 100644 index ffd1cbe365f..00000000000 --- a/samples/startup-shutdown-sequence/Core_9/Sample/ExtensionPoints/NeedInitialization.cs +++ /dev/null @@ -1,10 +0,0 @@ -using NServiceBus; - -public class NeedInitialization : - INeedInitialization -{ - public void Customize(EndpointConfiguration endpointConfiguration) - { - Logger.WriteLine("Inside INeedInitialization.Customize"); - } -} \ No newline at end of file diff --git a/samples/startup-shutdown-sequence/Core_9/Sample/ExtensionPoints/NeedToInstallSomething.cs b/samples/startup-shutdown-sequence/Core_9/Sample/ExtensionPoints/NeedToInstallSomething.cs deleted file mode 100644 index 73e8e22110e..00000000000 --- a/samples/startup-shutdown-sequence/Core_9/Sample/ExtensionPoints/NeedToInstallSomething.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Threading; -using System.Threading.Tasks; -using NServiceBus.Installation; - -public class NeedToInstallSomething : - INeedToInstallSomething -{ - public Task Install(string identity, CancellationToken token) - { - Logger.WriteLine("Inside INeedToInstallSomething.Install"); - return Task.CompletedTask; - } -} \ No newline at end of file diff --git a/samples/startup-shutdown-sequence/Core_9/Sample/ExtensionPoints/WantToRunBeforeConfigurationIsFinalized.cs b/samples/startup-shutdown-sequence/Core_9/Sample/ExtensionPoints/WantToRunBeforeConfigurationIsFinalized.cs deleted file mode 100644 index 4b616757a1e..00000000000 --- a/samples/startup-shutdown-sequence/Core_9/Sample/ExtensionPoints/WantToRunBeforeConfigurationIsFinalized.cs +++ /dev/null @@ -1,11 +0,0 @@ -using NServiceBus; -using NServiceBus.Settings; - -public class WantToRunBeforeConfigurationIsFinalized : - IWantToRunBeforeConfigurationIsFinalized -{ - public void Run(SettingsHolder settings) - { - Logger.WriteLine("Inside WantToRunBeforeConfigurationIsFinalized.Run"); - } -} \ No newline at end of file diff --git a/samples/startup-shutdown-sequence/Core_9/Sample/Logger.cs b/samples/startup-shutdown-sequence/Core_9/Sample/Logger.cs deleted file mode 100644 index 286a391e82c..00000000000 --- a/samples/startup-shutdown-sequence/Core_9/Sample/Logger.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.IO; -using System.Threading; -using NServiceBus.Logging; - -#region Logger -static class Logger -{ - static ILog log = LogManager.GetLogger(typeof(Logger)); - public static string OutputFilePath; - static object locker = new object(); - - static Logger() - { - OutputFilePath = Path.GetFullPath("StartupShutdownSequence.txt"); - AppDomain.CurrentDomain.ProcessExit += Exit; - File.Delete(OutputFilePath); - File.AppendAllText(OutputFilePath, "startcode"); - File.AppendAllText(OutputFilePath, " StartupShutdownSequence\r\n"); - } - - static void Exit(object sender, EventArgs e) - { - File.AppendAllText(OutputFilePath, "endcode"); - } - - public static void WriteLine(string message) - { - message = $"Thread:{Thread.CurrentThread.ManagedThreadId} {message}\r\n"; - log.Info(message); - lock (locker) - { - File.AppendAllText(OutputFilePath, message); - } - } - -} -#endregion \ No newline at end of file diff --git a/samples/startup-shutdown-sequence/Core_9/Sample/Program.cs b/samples/startup-shutdown-sequence/Core_9/Sample/Program.cs deleted file mode 100644 index aa399212f85..00000000000 --- a/samples/startup-shutdown-sequence/Core_9/Sample/Program.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; -using System.Threading.Tasks; -using NServiceBus; -using NServiceBus.Logging; - -class Program -{ - static async Task Main() - { - Console.Title = "StartupShutdown"; - LogManager.Use().Level(LogLevel.Error); - #region Program - Logger.WriteLine("Starting configuration"); - var endpointConfiguration = new EndpointConfiguration("Samples.StartupShutdown"); - endpointConfiguration.EnableInstallers(); - endpointConfiguration.EnableFeature(); - endpointConfiguration.UseSerialization(); - endpointConfiguration.UseTransport(new LearningTransport()); - - Logger.WriteLine("Calling Endpoint.Start"); - var endpointInstance = await Endpoint.Start(endpointConfiguration); - // simulate some activity - await Task.Delay(500); - - Logger.WriteLine("Endpoint is processing messages"); - Logger.WriteLine("Calling IEndpointInstance.Stop"); - await endpointInstance.Stop(); - Logger.WriteLine("Finished"); - #endregion - Console.WriteLine($"Logged information to {Logger.OutputFilePath}"); - Console.WriteLine("Press any key to exit"); - Console.ReadKey(); - } -} diff --git a/samples/startup-shutdown-sequence/Core_9/Sample/Sample.csproj b/samples/startup-shutdown-sequence/Core_9/Sample/Sample.csproj deleted file mode 100644 index 6adf3962cf3..00000000000 --- a/samples/startup-shutdown-sequence/Core_9/Sample/Sample.csproj +++ /dev/null @@ -1,10 +0,0 @@ - - - net10.0;net9.0;net8.0 - Exe - 12.0 - - - - - \ No newline at end of file diff --git a/samples/startup-shutdown-sequence/Core_9/StartupShutdown.sln b/samples/startup-shutdown-sequence/Core_9/StartupShutdown.sln deleted file mode 100644 index 50055481477..00000000000 --- a/samples/startup-shutdown-sequence/Core_9/StartupShutdown.sln +++ /dev/null @@ -1,19 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29728.190 -MinimumVisualStudioVersion = 15.0.26730.12 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sample", "Sample\Sample.csproj", "{48F718EE-6C45-41BA-80EC-81BF34D4A623}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {48F718EE-6C45-41BA-80EC-81BF34D4A623}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {48F718EE-6C45-41BA-80EC-81BF34D4A623}.Debug|Any CPU.Build.0 = Debug|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/samples/startup-shutdown-sequence/Core_9/StartupShutdownSequence.txt b/samples/startup-shutdown-sequence/Core_9/StartupShutdownSequence.txt deleted file mode 100644 index a139f02287e..00000000000 --- a/samples/startup-shutdown-sequence/Core_9/StartupShutdownSequence.txt +++ /dev/null @@ -1,13 +0,0 @@ -startcode StartupShutdownSequence -Thread:1 Starting configuration -Thread:1 Calling Endpoint.Start -Thread:1 Inside INeedInitialization.Customize -Thread:1 Inside WantToRunBeforeConfigurationIsFinalized.Run -Thread:1 Inside Feature.Setup -Thread:1 Inside INeedToInstallSomething.Install -Thread:1 Inside FeatureStartupTask.OnStart -Thread:11 Endpoint is processing messages -Thread:11 Calling IEndpointInstance.Stop -Thread:7 Inside FeatureStartupTask.OnStop -Thread:7 Finished -endcode \ No newline at end of file diff --git a/samples/startup-shutdown-sequence/sample.md b/samples/startup-shutdown-sequence/sample.md deleted file mode 100644 index dd1d6409526..00000000000 --- a/samples/startup-shutdown-sequence/sample.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: Startup and Shutdown Sequence -summary: The sequence of steps in an endpoint startup and shutdown process, including all available public extension points -component: Core -reviewed: 2024-11-19 -related: -- nservicebus/operations/installers ---- - - -## Code walk-through - -The sample illustrates the order of startup and shutdown steps for an NServiceBus endpoint. All usages of the public extension points API are stored in the `ExtensionPoints` folder of the project. - - -## Logger - -For each step in the process, there is a corresponding log entry written both to the console and a text file. - -snippet: Logger - - -## Console program - -The main section of the console `Program` configures and starts the endpoint while logging all these actions. - -snippet: Program - - -### The resulting order - -> [!NOTE] -> In some versions of NServiceBus, certain extension points are executed on separate threads. - -snippet: StartupShutdownSequence diff --git a/samples/unit-testing/Testing_10/Sample/Data/MyController.cs b/samples/unit-testing/Testing_10/Sample/Data/MyController.cs index 463215bb199..75ab878b36f 100644 --- a/samples/unit-testing/Testing_10/Sample/Data/MyController.cs +++ b/samples/unit-testing/Testing_10/Sample/Data/MyController.cs @@ -2,18 +2,11 @@ using NServiceBus; #region Controller -public class MyController +public class MyController(IMessageSession messageSession) { - IEndpointInstance endpointInstance; - - public MyController(IEndpointInstance endpointInstance) - { - this.endpointInstance = endpointInstance; - } - public Task HandleRequest() { - return endpointInstance.Send(new MyMessage()); + return messageSession.Send(new MyMessage()); } } #endregion \ No newline at end of file diff --git a/samples/unit-testing/Testing_10/Sample/Sample.csproj b/samples/unit-testing/Testing_10/Sample/Sample.csproj index adc7f1ba3e8..a77e2224de7 100644 --- a/samples/unit-testing/Testing_10/Sample/Sample.csproj +++ b/samples/unit-testing/Testing_10/Sample/Sample.csproj @@ -5,7 +5,7 @@ - + diff --git a/samples/username-header/Core_10/Endpoint1/Endpoint1.csproj b/samples/username-header/Core_10/Endpoint1/Endpoint1.csproj deleted file mode 100644 index 9b393d2b71b..00000000000 --- a/samples/username-header/Core_10/Endpoint1/Endpoint1.csproj +++ /dev/null @@ -1,14 +0,0 @@ - - - net10.0 - 14.0 - Exe - enable - - - - - - - - \ No newline at end of file diff --git a/samples/username-header/Core_10/Endpoint1/Program.cs b/samples/username-header/Core_10/Endpoint1/Program.cs deleted file mode 100644 index 8730aa7dde9..00000000000 --- a/samples/username-header/Core_10/Endpoint1/Program.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System; -using System.Security.Principal; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using NServiceBus.MessageMutator; - -Console.Title = "Endpoint1"; - -var endpointConfiguration = new EndpointConfiguration("Samples.UsernameHeader.Endpoint1"); -endpointConfiguration.UseSerialization(); -endpointConfiguration.UseTransport(new LearningTransport()); - -var builder = Host.CreateApplicationBuilder(args); - -#region component-registration-sender - -// Register both services - -var principalAccessor = new PrincipalAccessor(); -builder.Services.AddSingleton(principalAccessor); - -var serviceProvider = builder.Services.BuildServiceProvider(); - -var logger = serviceProvider.GetRequiredService>(); -var mutator = new AddUserNameToOutgoingHeadersMutator(principalAccessor, logger); -endpointConfiguration.RegisterMessageMutator(mutator); -#endregion - -Console.WriteLine("Press any key, the application is starting"); -Console.ReadKey(); -Console.WriteLine("Starting..."); - -builder.UseNServiceBus(endpointConfiguration); - -var host = builder.Build(); - -await host.StartAsync(); - -#region send-message - -async Task SendMessage(int userNumber) -{ - var identity = new GenericIdentity($"FakeUser{userNumber}"); - principalAccessor.CurrentPrincipal = new GenericPrincipal(identity, []); - - var messageSession = host.Services.GetRequiredService(); - - var message = new MyMessage(); - await messageSession.Send("Samples.UsernameHeader.Endpoint2", message); -} - -await Task.WhenAll(SendMessage(1), SendMessage(2)); - -#endregion - -Console.WriteLine("Message sent. Press any key to exit"); -Console.ReadKey(); - -await host.StopAsync(); \ No newline at end of file diff --git a/samples/username-header/Core_10/Endpoint2/Endpoint2.csproj b/samples/username-header/Core_10/Endpoint2/Endpoint2.csproj deleted file mode 100644 index b7fabb0525a..00000000000 --- a/samples/username-header/Core_10/Endpoint2/Endpoint2.csproj +++ /dev/null @@ -1,14 +0,0 @@ - - - net10.0 - 14.0 - Exe - enable - - - - - - - - \ No newline at end of file diff --git a/samples/username-header/Core_10/Endpoint2/HandlerUsingAccessor.cs b/samples/username-header/Core_10/Endpoint2/HandlerUsingAccessor.cs deleted file mode 100644 index e32dc38f778..00000000000 --- a/samples/username-header/Core_10/Endpoint2/HandlerUsingAccessor.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Threading.Tasks; -using Microsoft.Extensions.Logging; -using NServiceBus; - -#region handler-using-custom-header - -public class HandlerUsingAccessor : - IHandleMessages -{ - readonly IPrincipalAccessor principalAccessor; - private readonly ILogger logger; - - public HandlerUsingAccessor(IPrincipalAccessor principalAccessor, ILogger logger) - { - this.principalAccessor = principalAccessor; - this.logger = logger; - } - - public Task Handle(MyMessage message, IMessageHandlerContext context) - { - var headers = context.MessageHeaders; - var usernameFromHeader = headers["UserName"]; - var usernameFromAccessor = principalAccessor?.CurrentPrincipal?.Identity?.Name ?? "null"; - logger.LogInformation("Username extracted from header: {UsernameFromHeader}", usernameFromHeader); - logger.LogInformation("Username extracted from accessor: {UsernameFromAccessor}", usernameFromAccessor); - return Task.CompletedTask; - } -} - -#endregion \ No newline at end of file diff --git a/samples/username-header/Core_10/Endpoint2/Program.cs b/samples/username-header/Core_10/Endpoint2/Program.cs deleted file mode 100644 index 6a07dcfa51a..00000000000 --- a/samples/username-header/Core_10/Endpoint2/Program.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using NServiceBus; -using NServiceBus.MessageMutator; - -Console.Title = "Endpoint2"; - -var builder = Host.CreateApplicationBuilder(args); - -var endpointConfiguration = new EndpointConfiguration("Samples.UsernameHeader.Endpoint2"); -endpointConfiguration.UseSerialization(); -endpointConfiguration.UseTransport(new LearningTransport()); - -#region component-registration-receiver -// Register both services -builder.Services.AddSingleton(); -builder.Services.AddSingleton(); - -var serviceProvider = builder.Services.BuildServiceProvider(); -var principalAccessor = serviceProvider.GetRequiredService(); // Use the interface type here -var mutator = serviceProvider.GetRequiredService(); - -endpointConfiguration.RegisterMessageMutator(mutator); - -endpointConfiguration.RegisterComponents(c => -{ - //Register the accessor in the container so that the handler can access it - c.AddSingleton(principalAccessor); -}); - -#endregion - -builder.UseNServiceBus(endpointConfiguration); -await builder.Build().RunAsync(); - diff --git a/samples/username-header/Core_10/Shared/AddUserNameToOutgoingHeadersMutator.cs b/samples/username-header/Core_10/Shared/AddUserNameToOutgoingHeadersMutator.cs deleted file mode 100644 index 940f8d6fa6d..00000000000 --- a/samples/username-header/Core_10/Shared/AddUserNameToOutgoingHeadersMutator.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System.Threading.Tasks; -using Microsoft.Extensions.Logging; -using NServiceBus.MessageMutator; - -#region username-header-mutator - -public class AddUserNameToOutgoingHeadersMutator: - IMutateOutgoingTransportMessages -{ - readonly IPrincipalAccessor principalAccessor; - private readonly ILogger logger; - - public AddUserNameToOutgoingHeadersMutator(IPrincipalAccessor principalAccessor, ILogger logger) - { - this.principalAccessor = principalAccessor; - this.logger = logger; - } - - public Task MutateOutgoing(MutateOutgoingTransportMessageContext context) - { - if (principalAccessor.CurrentPrincipal?.Identity.Name != null) - { - - logger.LogInformation("Adding CurrentPrincipal user to headers"); - context.OutgoingHeaders["UserName"] = principalAccessor.CurrentPrincipal.Identity.Name; - } - - return Task.CompletedTask; - } -} - -#endregion \ No newline at end of file diff --git a/samples/username-header/Core_10/Shared/IPrincipalAccessor.cs b/samples/username-header/Core_10/Shared/IPrincipalAccessor.cs deleted file mode 100644 index d8d4bb6a231..00000000000 --- a/samples/username-header/Core_10/Shared/IPrincipalAccessor.cs +++ /dev/null @@ -1,6 +0,0 @@ -using System.Security.Principal; - -public interface IPrincipalAccessor -{ - IPrincipal CurrentPrincipal { get; set; } -} \ No newline at end of file diff --git a/samples/username-header/Core_10/Shared/MyMessage.cs b/samples/username-header/Core_10/Shared/MyMessage.cs deleted file mode 100644 index 65952daa4c9..00000000000 --- a/samples/username-header/Core_10/Shared/MyMessage.cs +++ /dev/null @@ -1,6 +0,0 @@ -using NServiceBus; - -public class MyMessage : - IMessage -{ -} \ No newline at end of file diff --git a/samples/username-header/Core_10/Shared/PrincipalAccessor.cs b/samples/username-header/Core_10/Shared/PrincipalAccessor.cs deleted file mode 100644 index 86e4a6c5530..00000000000 --- a/samples/username-header/Core_10/Shared/PrincipalAccessor.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Security.Principal; -using System.Threading; - -public class PrincipalAccessor : IPrincipalAccessor -{ - AsyncLocal principalCurrent = new AsyncLocal(); - - public IPrincipal CurrentPrincipal - { - get - { - return principalCurrent.Value?.CurrentPrincipal; - } - set - { - var holder = principalCurrent.Value; - if (holder != null) - { - // Clear current IPrincipal trapped in the AsyncLocals, as its done. - holder.CurrentPrincipal = null; - } - - if (value != null) - { - // Use an object indirection to hold the IPrincipal in the AsyncLocal, - // so it can be cleared in all ExecutionContexts when its cleared. - principalCurrent.Value = new CurrentPrincipalHolder { CurrentPrincipal = value }; - } - } - } - - class CurrentPrincipalHolder - { - public IPrincipal CurrentPrincipal; - } -} diff --git a/samples/username-header/Core_10/Shared/SetCurrentPrincipalBasedOnHeaderMutator.cs b/samples/username-header/Core_10/Shared/SetCurrentPrincipalBasedOnHeaderMutator.cs deleted file mode 100644 index 4c93a28da59..00000000000 --- a/samples/username-header/Core_10/Shared/SetCurrentPrincipalBasedOnHeaderMutator.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System.Security.Principal; -using System.Threading.Tasks; -using Microsoft.Extensions.Logging; -using NServiceBus.MessageMutator; - -#region set-principal-from-header-mutator -public class SetCurrentPrincipalBasedOnHeaderMutator : - IMutateIncomingTransportMessages -{ - - readonly IPrincipalAccessor principalAccessor; - private readonly ILogger logger; - - public SetCurrentPrincipalBasedOnHeaderMutator(IPrincipalAccessor principalAccessor, ILogger logger) - { - this.principalAccessor = principalAccessor; - this.logger = logger; - } - - public Task MutateIncoming(MutateIncomingTransportMessageContext context) - { - if (context.Headers.TryGetValue("UserName", out var userNameHeader)) - { - logger.LogInformation("Adding CurrentPrincipal user from headers"); - var identity = new GenericIdentity(userNameHeader); - principalAccessor.CurrentPrincipal = new GenericPrincipal(identity, new string[0]); - } - - return Task.CompletedTask; - } -} -#endregion \ No newline at end of file diff --git a/samples/username-header/Core_10/Shared/Shared.csproj b/samples/username-header/Core_10/Shared/Shared.csproj deleted file mode 100644 index 21e57f9e46e..00000000000 --- a/samples/username-header/Core_10/Shared/Shared.csproj +++ /dev/null @@ -1,12 +0,0 @@ - - - net10.0 - 14.0 - enable - - - - - - - \ No newline at end of file diff --git a/samples/username-header/Core_10/UsernameHeader.sln b/samples/username-header/Core_10/UsernameHeader.sln deleted file mode 100644 index 1fdab81188e..00000000000 --- a/samples/username-header/Core_10/UsernameHeader.sln +++ /dev/null @@ -1,27 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29728.190 -MinimumVisualStudioVersion = 15.0.26730.12 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Endpoint1", "Endpoint1\Endpoint1.csproj", "{E94B7783-5A00-4C72-9C9B-B126D8E59314}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Endpoint2", "Endpoint2\Endpoint2.csproj", "{52D01D1A-0522-42A3-8C9B-3002B6C6757A}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Shared", "Shared\Shared.csproj", "{7B8DA931-9045-4A0C-A143-6F36F3175BBF}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {E94B7783-5A00-4C72-9C9B-B126D8E59314}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E94B7783-5A00-4C72-9C9B-B126D8E59314}.Debug|Any CPU.Build.0 = Debug|Any CPU - {52D01D1A-0522-42A3-8C9B-3002B6C6757A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {52D01D1A-0522-42A3-8C9B-3002B6C6757A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7B8DA931-9045-4A0C-A143-6F36F3175BBF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7B8DA931-9045-4A0C-A143-6F36F3175BBF}.Debug|Any CPU.Build.0 = Debug|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/samples/username-header/Core_9/Endpoint1/Endpoint1.csproj b/samples/username-header/Core_9/Endpoint1/Endpoint1.csproj deleted file mode 100644 index 5135f27dcc0..00000000000 --- a/samples/username-header/Core_9/Endpoint1/Endpoint1.csproj +++ /dev/null @@ -1,13 +0,0 @@ - - - net10.0;net9.0;net8.0 - Exe - 12.0 - - - - - - - - \ No newline at end of file diff --git a/samples/username-header/Core_9/Endpoint1/Program.cs b/samples/username-header/Core_9/Endpoint1/Program.cs deleted file mode 100644 index b632ebb2ac9..00000000000 --- a/samples/username-header/Core_9/Endpoint1/Program.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System; -using System.Security.Principal; -using System.Threading.Tasks; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using NServiceBus; -using NServiceBus.MessageMutator; - -Console.Title = "Endpoint1"; - -var endpointConfiguration = new EndpointConfiguration("Samples.UsernameHeader.Endpoint1"); -endpointConfiguration.UseSerialization(); -endpointConfiguration.UseTransport(new LearningTransport()); - -var builder = Host.CreateApplicationBuilder(args); - -#region component-registration-sender - -// Register both services - -var principalAccessor = new PrincipalAccessor(); -builder.Services.AddSingleton(principalAccessor); - -var serviceProvider = builder.Services.BuildServiceProvider(); - -var logger = serviceProvider.GetRequiredService>(); -var mutator = new AddUserNameToOutgoingHeadersMutator(principalAccessor, logger); -endpointConfiguration.RegisterMessageMutator(mutator); -#endregion - -Console.WriteLine("Press any key, the application is starting"); -Console.ReadKey(); -Console.WriteLine("Starting..."); - -builder.UseNServiceBus(endpointConfiguration); - -var host = builder.Build(); - -await host.StartAsync(); - -#region send-message - -async Task SendMessage(int userNumber) -{ - var identity = new GenericIdentity($"FakeUser{userNumber}"); - principalAccessor.CurrentPrincipal = new GenericPrincipal(identity, []); - - var messageSession = host.Services.GetRequiredService(); - - var message = new MyMessage(); - await messageSession.Send("Samples.UsernameHeader.Endpoint2", message); -} - -await Task.WhenAll(SendMessage(1), SendMessage(2)); - -#endregion - -Console.WriteLine("Message sent. Press any key to exit"); -Console.ReadKey(); - -await host.StopAsync(); \ No newline at end of file diff --git a/samples/username-header/Core_9/Endpoint2/Endpoint2.csproj b/samples/username-header/Core_9/Endpoint2/Endpoint2.csproj deleted file mode 100644 index 5135f27dcc0..00000000000 --- a/samples/username-header/Core_9/Endpoint2/Endpoint2.csproj +++ /dev/null @@ -1,13 +0,0 @@ - - - net10.0;net9.0;net8.0 - Exe - 12.0 - - - - - - - - \ No newline at end of file diff --git a/samples/username-header/Core_9/Endpoint2/HandlerUsingAccessor.cs b/samples/username-header/Core_9/Endpoint2/HandlerUsingAccessor.cs deleted file mode 100644 index e32dc38f778..00000000000 --- a/samples/username-header/Core_9/Endpoint2/HandlerUsingAccessor.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Threading.Tasks; -using Microsoft.Extensions.Logging; -using NServiceBus; - -#region handler-using-custom-header - -public class HandlerUsingAccessor : - IHandleMessages -{ - readonly IPrincipalAccessor principalAccessor; - private readonly ILogger logger; - - public HandlerUsingAccessor(IPrincipalAccessor principalAccessor, ILogger logger) - { - this.principalAccessor = principalAccessor; - this.logger = logger; - } - - public Task Handle(MyMessage message, IMessageHandlerContext context) - { - var headers = context.MessageHeaders; - var usernameFromHeader = headers["UserName"]; - var usernameFromAccessor = principalAccessor?.CurrentPrincipal?.Identity?.Name ?? "null"; - logger.LogInformation("Username extracted from header: {UsernameFromHeader}", usernameFromHeader); - logger.LogInformation("Username extracted from accessor: {UsernameFromAccessor}", usernameFromAccessor); - return Task.CompletedTask; - } -} - -#endregion \ No newline at end of file diff --git a/samples/username-header/Core_9/Endpoint2/Program.cs b/samples/username-header/Core_9/Endpoint2/Program.cs deleted file mode 100644 index a8eaa5d6075..00000000000 --- a/samples/username-header/Core_9/Endpoint2/Program.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System; -using System.Threading.Tasks; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using NServiceBus; -using NServiceBus.MessageMutator; - - -Console.Title = "Endpoint2"; - -var builder = Host.CreateApplicationBuilder(args); - -var endpointConfiguration = new EndpointConfiguration("Samples.UsernameHeader.Endpoint2"); -endpointConfiguration.UseSerialization(); -endpointConfiguration.UseTransport(new LearningTransport()); - -#region component-registration-receiver -// Register both services -builder.Services.AddSingleton(); -builder.Services.AddSingleton(); - -var serviceProvider = builder.Services.BuildServiceProvider(); -var principalAccessor = serviceProvider.GetRequiredService(); // Use the interface type here -var mutator = serviceProvider.GetRequiredService(); - -endpointConfiguration.RegisterMessageMutator(mutator); - -endpointConfiguration.RegisterComponents(c => -{ - //Register the accessor in the container so that the handler can access it - c.AddSingleton(principalAccessor); -}); - -#endregion - -Console.WriteLine("Press any key, the application is starting"); -Console.ReadKey(); -Console.WriteLine("Starting..."); - -builder.UseNServiceBus(endpointConfiguration); -await builder.Build().RunAsync(); - diff --git a/samples/username-header/Core_9/Shared/AddUserNameToOutgoingHeadersMutator.cs b/samples/username-header/Core_9/Shared/AddUserNameToOutgoingHeadersMutator.cs deleted file mode 100644 index 940f8d6fa6d..00000000000 --- a/samples/username-header/Core_9/Shared/AddUserNameToOutgoingHeadersMutator.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System.Threading.Tasks; -using Microsoft.Extensions.Logging; -using NServiceBus.MessageMutator; - -#region username-header-mutator - -public class AddUserNameToOutgoingHeadersMutator: - IMutateOutgoingTransportMessages -{ - readonly IPrincipalAccessor principalAccessor; - private readonly ILogger logger; - - public AddUserNameToOutgoingHeadersMutator(IPrincipalAccessor principalAccessor, ILogger logger) - { - this.principalAccessor = principalAccessor; - this.logger = logger; - } - - public Task MutateOutgoing(MutateOutgoingTransportMessageContext context) - { - if (principalAccessor.CurrentPrincipal?.Identity.Name != null) - { - - logger.LogInformation("Adding CurrentPrincipal user to headers"); - context.OutgoingHeaders["UserName"] = principalAccessor.CurrentPrincipal.Identity.Name; - } - - return Task.CompletedTask; - } -} - -#endregion \ No newline at end of file diff --git a/samples/username-header/Core_9/Shared/IPrincipalAccessor.cs b/samples/username-header/Core_9/Shared/IPrincipalAccessor.cs deleted file mode 100644 index d8d4bb6a231..00000000000 --- a/samples/username-header/Core_9/Shared/IPrincipalAccessor.cs +++ /dev/null @@ -1,6 +0,0 @@ -using System.Security.Principal; - -public interface IPrincipalAccessor -{ - IPrincipal CurrentPrincipal { get; set; } -} \ No newline at end of file diff --git a/samples/username-header/Core_9/Shared/MyMessage.cs b/samples/username-header/Core_9/Shared/MyMessage.cs deleted file mode 100644 index 65952daa4c9..00000000000 --- a/samples/username-header/Core_9/Shared/MyMessage.cs +++ /dev/null @@ -1,6 +0,0 @@ -using NServiceBus; - -public class MyMessage : - IMessage -{ -} \ No newline at end of file diff --git a/samples/username-header/Core_9/Shared/PrincipalAccessor.cs b/samples/username-header/Core_9/Shared/PrincipalAccessor.cs deleted file mode 100644 index 86e4a6c5530..00000000000 --- a/samples/username-header/Core_9/Shared/PrincipalAccessor.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Security.Principal; -using System.Threading; - -public class PrincipalAccessor : IPrincipalAccessor -{ - AsyncLocal principalCurrent = new AsyncLocal(); - - public IPrincipal CurrentPrincipal - { - get - { - return principalCurrent.Value?.CurrentPrincipal; - } - set - { - var holder = principalCurrent.Value; - if (holder != null) - { - // Clear current IPrincipal trapped in the AsyncLocals, as its done. - holder.CurrentPrincipal = null; - } - - if (value != null) - { - // Use an object indirection to hold the IPrincipal in the AsyncLocal, - // so it can be cleared in all ExecutionContexts when its cleared. - principalCurrent.Value = new CurrentPrincipalHolder { CurrentPrincipal = value }; - } - } - } - - class CurrentPrincipalHolder - { - public IPrincipal CurrentPrincipal; - } -} diff --git a/samples/username-header/Core_9/Shared/SetCurrentPrincipalBasedOnHeaderMutator.cs b/samples/username-header/Core_9/Shared/SetCurrentPrincipalBasedOnHeaderMutator.cs deleted file mode 100644 index 4c93a28da59..00000000000 --- a/samples/username-header/Core_9/Shared/SetCurrentPrincipalBasedOnHeaderMutator.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System.Security.Principal; -using System.Threading.Tasks; -using Microsoft.Extensions.Logging; -using NServiceBus.MessageMutator; - -#region set-principal-from-header-mutator -public class SetCurrentPrincipalBasedOnHeaderMutator : - IMutateIncomingTransportMessages -{ - - readonly IPrincipalAccessor principalAccessor; - private readonly ILogger logger; - - public SetCurrentPrincipalBasedOnHeaderMutator(IPrincipalAccessor principalAccessor, ILogger logger) - { - this.principalAccessor = principalAccessor; - this.logger = logger; - } - - public Task MutateIncoming(MutateIncomingTransportMessageContext context) - { - if (context.Headers.TryGetValue("UserName", out var userNameHeader)) - { - logger.LogInformation("Adding CurrentPrincipal user from headers"); - var identity = new GenericIdentity(userNameHeader); - principalAccessor.CurrentPrincipal = new GenericPrincipal(identity, new string[0]); - } - - return Task.CompletedTask; - } -} -#endregion \ No newline at end of file diff --git a/samples/username-header/Core_9/Shared/Shared.csproj b/samples/username-header/Core_9/Shared/Shared.csproj deleted file mode 100644 index 838faa252b6..00000000000 --- a/samples/username-header/Core_9/Shared/Shared.csproj +++ /dev/null @@ -1,10 +0,0 @@ - - - net10.0;net9.0;net8.0 - 12.0 - - - - - - \ No newline at end of file diff --git a/samples/username-header/Core_9/UsernameHeader.sln b/samples/username-header/Core_9/UsernameHeader.sln deleted file mode 100644 index 1fdab81188e..00000000000 --- a/samples/username-header/Core_9/UsernameHeader.sln +++ /dev/null @@ -1,27 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29728.190 -MinimumVisualStudioVersion = 15.0.26730.12 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Endpoint1", "Endpoint1\Endpoint1.csproj", "{E94B7783-5A00-4C72-9C9B-B126D8E59314}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Endpoint2", "Endpoint2\Endpoint2.csproj", "{52D01D1A-0522-42A3-8C9B-3002B6C6757A}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Shared", "Shared\Shared.csproj", "{7B8DA931-9045-4A0C-A143-6F36F3175BBF}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {E94B7783-5A00-4C72-9C9B-B126D8E59314}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E94B7783-5A00-4C72-9C9B-B126D8E59314}.Debug|Any CPU.Build.0 = Debug|Any CPU - {52D01D1A-0522-42A3-8C9B-3002B6C6757A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {52D01D1A-0522-42A3-8C9B-3002B6C6757A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7B8DA931-9045-4A0C-A143-6F36F3175BBF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7B8DA931-9045-4A0C-A143-6F36F3175BBF}.Debug|Any CPU.Build.0 = Debug|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/samples/username-header/sample.md b/samples/username-header/sample.md deleted file mode 100644 index 01929c29294..00000000000 --- a/samples/username-header/sample.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -title: Passing user identity between endpoints using a custom header -summary: How to pass user identity between sending and receiving endpoints by attaching a custom header to every outgoing message. -reviewed: 2024-12-10 -component: Core -related: -- nservicebus/pipeline/message-mutators -- nservicebus/messaging/headers ---- - -This sample demonstrates how to attach the current user identity (username) to all outgoing messages and how to extract that value when messages are received. User identity is accessed by a current principal accessor, registered through dependency injection. - -> [!NOTE] -> This sample doesn't use `Thread.CurrentPrincipal`. When used in asynchronous code, `Thread.CurrentPrincipal` depends on the version of the .NET runtime. Refer to [the Microsoft guidelines](https://docs.microsoft.com/en-us/aspnet/core/migration/claimsprincipal-current) for more details. - -### Fake principal - -The sample replaces the `principalAccessor.CurrentPrincipal` before sending a message with an ad-hoc value. In a production scenario, the `principalAccessor.CurrentPrincipal` would likely be set by the hosting environment e.g. IIS, and not in the user code. - -snippet: send-message - -The snippet above uses two asynchronous sends to demonstrate that the current principle is properly propagated into the message session. - -## Custom header with a mutator - -The recommended approach for capturing user information is to create a transport mutator extracting the current identity that adds it to the header collection of every outgoing message. - -### Outgoing message mutator - -The outgoing mutator extracts `principalAccessor.CurrentPrincipal.Identity.Name` and adds it to the message headers collection. - -snippet: username-header-mutator - -#### Register the outgoing message mutator - -snippet: component-registration-sender - -### Incoming message mutator - -The incoming mutator extracts the username header from the message and sets the `principalAccessor.CurrentPrincipal`. - -snippet: set-principal-from-header-mutator - -#### Register the incoming message mutator - -snippet: component-registration-receiver - -This sample doesn't register the outgoing message mutator for the receiver. If desired, the outgoing message mutator could be registered on the receiver as well. - -### The Handler - -From within a handler (or saga), the header value holding user identity can be accessed in the following way: - -snippet: handler-using-custom-header diff --git a/samples/versioning/Core_10/Publisher/Program.cs b/samples/versioning/Core_10/Publisher/Program.cs index 9269ae205e7..58a46a3c269 100644 --- a/samples/versioning/Core_10/Publisher/Program.cs +++ b/samples/versioning/Core_10/Publisher/Program.cs @@ -1,4 +1,6 @@ using Contracts; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; var endpointName = "Publisher"; Console.Title = endpointName; @@ -7,7 +9,11 @@ endpointConfiguration.UseSerialization(); endpointConfiguration.UseTransport(new LearningTransport()); -var endpointInstance = await Endpoint.Start(endpointConfiguration); +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); +var host = builder.Build(); +var messageSession = host.Services.GetRequiredService(); +await host.StartAsync(); Console.WriteLine("Press enter to publish a message"); Console.WriteLine("Press any key to exit"); @@ -21,7 +27,7 @@ break; } - await endpointInstance.Publish(sh => + await messageSession.Publish(sh => { sh.SomeData = 1; sh.MoreInfo = "It's a secret."; @@ -30,4 +36,4 @@ await endpointInstance.Publish(sh => Console.WriteLine("Published event."); } -await endpointInstance.Stop(); \ No newline at end of file +await host.StopAsync(); \ No newline at end of file diff --git a/samples/versioning/Core_10/V1.Contracts/Contracts.csproj b/samples/versioning/Core_10/V1.Contracts/Contracts.csproj index 2a73a69aa0c..a616858291e 100644 --- a/samples/versioning/Core_10/V1.Contracts/Contracts.csproj +++ b/samples/versioning/Core_10/V1.Contracts/Contracts.csproj @@ -6,6 +6,6 @@ 1.0.0 - + \ No newline at end of file diff --git a/samples/versioning/Core_10/V1.Subscriber/Program.cs b/samples/versioning/Core_10/V1.Subscriber/Program.cs index b6ae6acfd7e..8adc96b9481 100644 --- a/samples/versioning/Core_10/V1.Subscriber/Program.cs +++ b/samples/versioning/Core_10/V1.Subscriber/Program.cs @@ -8,9 +8,6 @@ endpointConfiguration.UseSerialization(); endpointConfiguration.UseTransport(new LearningTransport()); -Console.WriteLine("Press any key"); -Console.ReadKey(); - -builder.UseNServiceBus(endpointConfiguration); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); await builder.Build().RunAsync(); \ No newline at end of file diff --git a/samples/versioning/Core_10/V1.Subscriber/V1.Subscriber.csproj b/samples/versioning/Core_10/V1.Subscriber/V1.Subscriber.csproj index f8e4688ea3a..9814531f324 100644 --- a/samples/versioning/Core_10/V1.Subscriber/V1.Subscriber.csproj +++ b/samples/versioning/Core_10/V1.Subscriber/V1.Subscriber.csproj @@ -8,7 +8,4 @@ - - - \ No newline at end of file diff --git a/samples/versioning/Core_10/V2.Contracts/Contracts.csproj b/samples/versioning/Core_10/V2.Contracts/Contracts.csproj index 414286c7c34..2fe41862d32 100644 --- a/samples/versioning/Core_10/V2.Contracts/Contracts.csproj +++ b/samples/versioning/Core_10/V2.Contracts/Contracts.csproj @@ -6,6 +6,6 @@ 2.0.0 - + \ No newline at end of file diff --git a/samples/versioning/Core_10/V2.Subscriber/Program.cs b/samples/versioning/Core_10/V2.Subscriber/Program.cs index 16473d6ca2c..965420f7239 100644 --- a/samples/versioning/Core_10/V2.Subscriber/Program.cs +++ b/samples/versioning/Core_10/V2.Subscriber/Program.cs @@ -3,14 +3,11 @@ var endpointName = "V2.Subscriber"; Console.Title = endpointName; var builder = Host.CreateApplicationBuilder(args); + var endpointConfiguration = new EndpointConfiguration(endpointName); endpointConfiguration.UseSerialization(); endpointConfiguration.UseTransport(new LearningTransport()); -Console.WriteLine("Press any key"); -Console.ReadKey(); - - -builder.UseNServiceBus(endpointConfiguration); +builder.Services.AddNServiceBusEndpoint(endpointConfiguration); await builder.Build().RunAsync(); \ No newline at end of file diff --git a/samples/versioning/Core_10/V2.Subscriber/V2.Subscriber.csproj b/samples/versioning/Core_10/V2.Subscriber/V2.Subscriber.csproj index dedce8fac3c..9097f0f5f5d 100644 --- a/samples/versioning/Core_10/V2.Subscriber/V2.Subscriber.csproj +++ b/samples/versioning/Core_10/V2.Subscriber/V2.Subscriber.csproj @@ -8,7 +8,4 @@ - - - \ No newline at end of file