public async Task Handle(OrderSubmitted message, IMessageHandlerContext context) { log.InfoFormat("Order {0} worth {1} submitted", message.OrderId, message.Value); #region StoreUserData ISession storageContext = context.SynchronizedStorageSession.Session(); using (ReceiverDataContext ctx = new ReceiverDataContext(storageContext.Connection)) { DbTransaction tx = ExtractTransactionFromSession(storageContext); ctx.Database.UseTransaction(tx); ctx.Orders.Add(new Order { OrderId = message.OrderId, Value = message.Value }); ctx.SaveChanges(); } #endregion #region Reply await context.Reply(new OrderAccepted { OrderId = message.OrderId, }); #endregion }
public void Handle(OrderSubmitted message) { log.InfoFormat("Order {0} worth {1} submitted", message.OrderId, message.Value); #region StoreUserData using (ReceiverDataContext ctx = new ReceiverDataContext(storageContext.Connection)) { ctx.Database.UseTransaction((DbTransaction)storageContext.DatabaseTransaction); ctx.Orders.Add(new Order { OrderId = message.OrderId, Value = message.Value }); ctx.SaveChanges(); } #endregion #region Reply bus.Reply(new OrderAccepted { OrderId = message.OrderId, }); #endregion }
public void Handle(OrderSubmitted message) { log.Info($"Order {message.OrderId} worth {message.Value} submitted"); #region StoreUserData var dbConnection = (SqlConnection)storageContext.Connection; using (var receiverDataContext = new ReceiverDataContext(dbConnection)) { var dbTransaction = (DbTransaction)storageContext.DatabaseTransaction; receiverDataContext.Database.UseTransaction(dbTransaction); var order = new Order { OrderId = message.OrderId, Value = message.Value }; receiverDataContext.Orders.Add(order); receiverDataContext.SaveChanges(); } #endregion #region Reply var orderAccepted = new OrderAccepted { OrderId = message.OrderId, }; bus.Reply(orderAccepted); #endregion }
static async Task AsyncMain() { Console.Title = "Samples.EntityFrameworkUnitOfWork.Receiver"; using (var receiverDataContext = new ReceiverDataContext()) { receiverDataContext.Database.Initialize(true); } var hibernateConfig = new Configuration(); hibernateConfig.DataBaseIntegration(x => { x.ConnectionStringName = "NServiceBus/Persistence"; x.Dialect <MsSql2012Dialect>(); }); hibernateConfig.SetProperty("default_schema", "receiver"); var endpointConfiguration = new EndpointConfiguration("Samples.EntityFrameworkUnitOfWork.Receiver"); endpointConfiguration.UseSerialization <JsonSerializer>(); endpointConfiguration.EnableInstallers(); endpointConfiguration.SendFailedMessagesTo("error"); var transport = endpointConfiguration.UseTransport <SqlServerTransport>(); var routing = transport.Routing(); routing.RouteToEndpoint(typeof(OrderAccepted).Assembly, "Samples.EntityFrameworkUnitOfWork.Sender"); routing.RegisterPublisher(typeof(OrderAccepted).Assembly, "Samples.EntityFrameworkUnitOfWork.Sender"); transport.DefaultSchema("receiver"); transport.UseSchemaForEndpoint("Samples.EntityFrameworkUnitOfWork.Sender", "sender"); transport.UseSchemaForQueue("error", "dbo"); transport.UseSchemaForQueue("audit", "dbo"); endpointConfiguration.UsePersistence <NHibernatePersistence>(); #region ReceiverConfiguration var pipeline = endpointConfiguration.Pipeline; pipeline.Register(new UnitOfWorkSetupBehaviorBehavior(), "Sets up unit of work for the message"); #endregion var endpointInstance = await Endpoint.Start(endpointConfiguration) .ConfigureAwait(false); try { Console.WriteLine("Press any key to exit"); Console.ReadKey(); } finally { await endpointInstance.Stop() .ConfigureAwait(false); } }
public async Task Handle(OrderSubmitted message, IMessageHandlerContext context) { log.Info($"Order {message.OrderId} worth {message.Value} submitted"); #region StoreUserData var storageContext = context.SynchronizedStorageSession.SqlPersistenceSession(); var dbConnection = storageContext.Connection; using (var receiverDataContext = new ReceiverDataContext(dbConnection)) { receiverDataContext.Database.UseTransaction(storageContext.Transaction); var order = new Order { OrderId = message.OrderId, Value = message.Value }; receiverDataContext.Orders.Add(order); await receiverDataContext.SaveChangesAsync() .ConfigureAwait(false); } #endregion #region Reply var orderAccepted = new OrderAccepted { OrderId = message.OrderId, }; await context.Reply(orderAccepted) .ConfigureAwait(false); #endregion }
static void Main() { using (ReceiverDataContext ctx = new ReceiverDataContext()) { ctx.Database.Initialize(true); } #region ReceiverConfiguration BusConfiguration busConfiguration = new BusConfiguration(); busConfiguration.UseTransport <SqlServerTransport>().UseSpecificConnectionInformation( EndpointConnectionInfo.For("sender") .UseConnectionString(@"Data Source=.\SQLEXPRESS;Initial Catalog=sender;Integrated Security=True")); busConfiguration.UsePersistence <NHibernatePersistence>().RegisterManagedSessionInTheContainer(); busConfiguration.EnableOutbox(); #endregion using (Bus.Create(busConfiguration).Start()) { Console.WriteLine("Press <enter> to exit"); Console.ReadLine(); } }
public void Handle(OrderSubmitted message) { log.InfoFormat("Order {0} worth {1} submitted", message.OrderId, message.Value); #region StoreUserData using (var receiverDataContext = new ReceiverDataContext(storageContext.Connection)) { receiverDataContext.Database.UseTransaction((DbTransaction)storageContext.DatabaseTransaction); var order = new Order { OrderId = message.OrderId, Value = message.Value }; receiverDataContext.Orders.Add(order); receiverDataContext.SaveChanges(); } #endregion #region Reply var orderAccepted = new OrderAccepted { OrderId = message.OrderId, }; bus.Reply(orderAccepted); #endregion }
static async Task Main() { var connectionString = @"Data Source=.\sqlexpress;Database=NsbSamplesEfUowSql;Integrated Security=True;Max Pool Size=100"; Console.Title = "Samples.EntityFrameworkUnitOfWork.SQL"; using (var connection = new SqlConnection(connectionString)) { using (var receiverDataContext = new ReceiverDataContext(connection)) { Database.SetInitializer(new CreateDatabaseIfNotExists <ReceiverDataContext>()); receiverDataContext.Database.Initialize(true); } } var endpointConfiguration = new EndpointConfiguration("Samples.EntityFrameworkUnitOfWork.SQL"); endpointConfiguration.EnableInstallers(); endpointConfiguration.SendFailedMessagesTo("error"); endpointConfiguration.ExecuteTheseHandlersFirst(typeof(CreateOrderHandler), typeof(OrderLifecycleSaga), typeof(CreateShipmentHandler)); endpointConfiguration.UseTransport(new SqlServerTransport(connectionString) { TransportTransactionMode = TransportTransactionMode.SendsAtomicWithReceive, Subscriptions = { DisableCaching = true } }); var persistence = endpointConfiguration.UsePersistence <SqlPersistence>(); persistence.ConnectionBuilder(() => new SqlConnection(connectionString)); var dialect = persistence.SqlDialect <SqlDialect.MsSqlServer>(); #region UnitOfWork_SQL endpointConfiguration.RegisterComponents(c => { c.AddScoped(b => { var session = b.GetRequiredService <ISqlStorageSession>(); var context = new ReceiverDataContext(session.Connection); //Use the same underlying ADO.NET transaction context.Database.UseTransaction(session.Transaction); //Ensure context is flushed before the transaction is committed session.OnSaveChanges(s => context.SaveChangesAsync()); return(context); }); }); #endregion var endpointInstance = await Endpoint.Start(endpointConfiguration) .ConfigureAwait(false); await Sender.Start(endpointInstance); }
static async Task AsyncMain() { Console.Title = "Samples.SQLNHibernateOutboxEF.Receiver"; using (var receiverDataContext = new ReceiverDataContext()) { receiverDataContext.Database.Initialize(true); } var hibernateConfig = new Configuration(); hibernateConfig.DataBaseIntegration(x => { x.ConnectionStringName = "NServiceBus/Persistence"; x.Dialect <MsSql2012Dialect>(); }); hibernateConfig.SetProperty("default_schema", "receiver"); var endpointConfiguration = new EndpointConfiguration("Samples.SQLNHibernateOutboxEF.Receiver"); endpointConfiguration.UseSerialization <JsonSerializer>(); #region ReceiverConfiguration var transport = endpointConfiguration.UseTransport <SqlServerTransport>(); transport.DefaultSchema("receiver"); transport.UseSpecificSchema(queueName => { if (queueName.Equals("error", StringComparison.OrdinalIgnoreCase) || queueName.Equals("audit", StringComparison.OrdinalIgnoreCase)) { return("dbo"); } if (queueName.Equals("Samples.SQLNHibernateOutboxEF.Sender", StringComparison.OrdinalIgnoreCase)) { return("sender"); } return(null); }); endpointConfiguration .UsePersistence <NHibernatePersistence>(); endpointConfiguration.EnableOutbox(); #endregion var endpointInstance = await Endpoint.Start(endpointConfiguration) .ConfigureAwait(false); try { Console.WriteLine("Press any key to exit"); Console.ReadKey(); } finally { await endpointInstance.Stop() .ConfigureAwait(false); } }
static void Main() { using (ReceiverDataContext ctx = new ReceiverDataContext()) { ctx.Database.Initialize(true); } #region ReceiverConfiguration BusConfiguration busConfiguration = new BusConfiguration(); busConfiguration.UseTransport<SqlServerTransport>().UseSpecificConnectionInformation( EndpointConnectionInfo.For("sender") .UseConnectionString(@"Data Source=.\SQLEXPRESS;Initial Catalog=sender;Integrated Security=True")); busConfiguration.UsePersistence<NHibernatePersistence>().RegisterManagedSessionInTheContainer(); busConfiguration.EnableOutbox(); #endregion using (Bus.Create(busConfiguration).Start()) { Console.WriteLine("Press <enter> to exit"); Console.ReadLine(); } }
static async Task Main() { var connection = @"Data Source=(local);Database=.\sqlexpress;Integrated Security=True;Max Pool Size=100"; Console.Title = "Samples.EntityFrameworkUnitOfWork.SQL"; using (var receiverDataContext = new ReceiverDataContext(new DbContextOptionsBuilder <ReceiverDataContext>() .UseSqlServer(new SqlConnection(connection)) .Options)) { await receiverDataContext.Database.EnsureCreatedAsync().ConfigureAwait(false); } var endpointConfiguration = new EndpointConfiguration("Samples.EntityFrameworkUnitOfWork.SQL"); endpointConfiguration.EnableInstallers(); endpointConfiguration.SendFailedMessagesTo("error"); endpointConfiguration.ExecuteTheseHandlersFirst(typeof(CreateOrderHandler), typeof(OrderLifecycleSaga), typeof(CreateShipmentHandler)); var transport = endpointConfiguration.UseTransport <SqlServerTransport>(); transport.ConnectionString(connection); transport.NativeDelayedDelivery().DisableTimeoutManagerCompatibility(); transport.SubscriptionSettings().DisableSubscriptionCache(); var persistence = endpointConfiguration.UsePersistence <SqlPersistence>(); persistence.ConnectionBuilder(() => new SqlConnection(connection)); var dialect = persistence.SqlDialect <SqlDialect.MsSqlServer>(); #region UnitOfWork_SQL endpointConfiguration.RegisterComponents(c => { c.ConfigureComponent(b => { var session = b.Build <ISqlStorageSession>(); var context = new ReceiverDataContext(new DbContextOptionsBuilder <ReceiverDataContext>() .UseSqlServer(session.Connection) .Options); //Use the same underlying ADO.NET transaction context.Database.UseTransaction(session.Transaction); //Ensure context is flushed before the transaction is committed session.OnSaveChanges(s => context.SaveChangesAsync()); return(context); }, DependencyLifecycle.InstancePerUnitOfWork); }); #endregion var endpointInstance = await Endpoint.Start(endpointConfiguration) .ConfigureAwait(false); await Sender.Start(endpointInstance); }
public ReceiverDataContext GetDataContext(SynchronizedStorageSession storageSession) { if (context == null) { context = contextFactory(storageSession); } return(context); }
static async Task Main() { var connection = @"Data Source=.\SqlExpress;Database=NsbSamplesEfUowNh;Integrated Security=True;Max Pool Size=100"; Console.Title = "Samples.EntityFrameworkUnitOfWork.NHibernate"; using (var receiverDataContext = new ReceiverDataContext(new SqlConnection(connection))) { Database.SetInitializer(new CreateDatabaseIfNotExists <ReceiverDataContext>()); receiverDataContext.Database.Initialize(true); } var endpointConfiguration = new EndpointConfiguration("Samples.EntityFrameworkUnitOfWork.NHibernate"); endpointConfiguration.EnableInstallers(); endpointConfiguration.SendFailedMessagesTo("error"); endpointConfiguration.Recoverability().DisableLegacyRetriesSatellite(); endpointConfiguration.ExecuteTheseHandlersFirst(typeof(CreateOrderHandler), typeof(OrderLifecycleSaga), typeof(CreateShipmentHandler)); var transport = endpointConfiguration.UseTransport <SqlServerTransport>(); transport.ConnectionString(connection); transport.UseNativeDelayedDelivery().DisableTimeoutManagerCompatibility(); var persistence = endpointConfiguration.UsePersistence <NHibernatePersistence>(); var hibernateConfig = new Configuration(); hibernateConfig.DataBaseIntegration(x => { x.ConnectionString = connection; x.Dialect <MsSql2012Dialect>(); }); persistence.UseConfiguration(hibernateConfig); #region UnitOfWork_NHibernate var pipeline = endpointConfiguration.Pipeline; pipeline.Register(new UnitOfWorkSetupBehaviorBehavior(storageSession => { var dbConnection = storageSession.Session().Connection; var context = new ReceiverDataContext(dbConnection); //Don't use transaction because connection is enlisted in the TransactionScope context.Database.UseTransaction(null); //Call SaveChanges before completing storage session storageSession.OnSaveChanges(x => context.SaveChangesAsync()); return(context); }), "Sets up unit of work for the message"); #endregion var endpointInstance = await Endpoint.Start(endpointConfiguration) .ConfigureAwait(false); await Sender.Start(endpointInstance); }
static async Task Main() { var connection = @"Data Source=.\SqlExpress;Database=NsbSamplesEfUowSql;Integrated Security=True;Max Pool Size=100"; Console.Title = "Samples.EntityFrameworkUnitOfWork.SQL"; using (var receiverDataContext = new ReceiverDataContext(new DbContextOptionsBuilder <ReceiverDataContext>() .UseSqlServer(new SqlConnection(connection)) .Options)) { await receiverDataContext.Database.EnsureCreatedAsync().ConfigureAwait(false); } var endpointConfiguration = new EndpointConfiguration("Samples.EntityFrameworkUnitOfWork.SQL"); endpointConfiguration.EnableInstallers(); endpointConfiguration.SendFailedMessagesTo("error"); endpointConfiguration.ExecuteTheseHandlersFirst(typeof(CreateOrderHandler), typeof(OrderLifecycleSaga), typeof(CreateShipmentHandler)); var transport = endpointConfiguration.UseTransport <SqlServerTransport>(); transport.ConnectionString(connection); transport.NativeDelayedDelivery().DisableTimeoutManagerCompatibility(); transport.SubscriptionSettings().DisableSubscriptionCache(); var persistence = endpointConfiguration.UsePersistence <SqlPersistence>(); persistence.ConnectionBuilder(() => new SqlConnection(connection)); var dialect = persistence.SqlDialect <SqlDialect.MsSqlServer>(); #region UnitOfWork_SQL var pipeline = endpointConfiguration.Pipeline; pipeline.Register(new UnitOfWorkSetupBehavior(storageSession => { var dbConnection = storageSession.SqlPersistenceSession().Connection; var context = new ReceiverDataContext(new DbContextOptionsBuilder <ReceiverDataContext>() .UseSqlServer(dbConnection) .Options); //Use the same underlying ADO.NET transaction context.Database.UseTransaction(storageSession.SqlPersistenceSession().Transaction); //Call SaveChanges before completing storage session storageSession.SqlPersistenceSession().OnSaveChanges(x => context.SaveChangesAsync()); return(context); }), "Sets up unit of work for the message"); #endregion var endpointInstance = await Endpoint.Start(endpointConfiguration) .ConfigureAwait(false); await Sender.Start(endpointInstance); }
static async Task AsyncMain() { Console.Title = "Samples.SQLNHibernateOutboxEF.Receiver"; using (ReceiverDataContext ctx = new ReceiverDataContext()) { ctx.Database.Initialize(true); } Configuration hibernateConfig = new Configuration(); hibernateConfig.DataBaseIntegration(x => { x.ConnectionStringName = "NServiceBus/Persistence"; x.Dialect<MsSql2012Dialect>(); }); hibernateConfig.SetProperty("default_schema", "receiver"); EndpointConfiguration endpointConfiguration = new EndpointConfiguration("Samples.SQLNHibernateOutboxEF.Receiver"); endpointConfiguration.UseSerialization<JsonSerializer>(); #region ReceiverConfiguration endpointConfiguration .UseTransport<SqlServerTransport>() .DefaultSchema("receiver") .UseSpecificSchema(queueName => { if (queueName.Equals("error", StringComparison.OrdinalIgnoreCase) || queueName.Equals("audit", StringComparison.OrdinalIgnoreCase)) { return "dbo"; } if (queueName.Equals("Samples.SQLNHibernateOutboxEF.Sender", StringComparison.OrdinalIgnoreCase)) { return "sender"; } return null; }); endpointConfiguration .UsePersistence<NHibernatePersistence>(); endpointConfiguration.EnableOutbox(); #endregion IEndpointInstance endpoint = await Endpoint.Start(endpointConfiguration); try { Console.WriteLine("Press any key to exit"); Console.ReadKey(); } finally { await endpoint.Stop(); } }
static async Task AsyncMain() { Console.Title = "Samples.SQLOutboxEF.Receiver"; var connectionString = @"Data Source=.\SqlExpress;Database=nservicebus;Integrated Security=True"; using (var receiverDataContext = new ReceiverDataContext(connectionString)) { receiverDataContext.Database.Initialize(true); } var endpointConfiguration = new EndpointConfiguration("Samples.SQLOutboxEF.Receiver"); endpointConfiguration.UseSerialization <JsonSerializer>(); endpointConfiguration.EnableInstallers(); #region ReceiverConfiguration var transport = endpointConfiguration.UseTransport <SqlServerTransport>(); transport.ConnectionString(connectionString); transport.DefaultSchema("receiver"); transport.UseSchemaForEndpoint("Samples.SQLOutboxEF.Sender", "sender"); transport.UseSchemaForQueue("error", "dbo"); transport.UseSchemaForQueue("audit", "dbo"); var routing = transport.Routing(); routing.RouteToEndpoint(typeof(OrderAccepted).Assembly, "Samples.SQLOutboxEF.Sender"); routing.RegisterPublisher(typeof(OrderAccepted).Assembly, "Samples.SQLOutboxEF.Sender"); var persistence = endpointConfiguration.UsePersistence <SqlPersistence>(); persistence.ConnectionBuilder( connectionBuilder: () => { return(new SqlConnection(connectionString)); }); persistence.TablePrefix("receiver."); endpointConfiguration.EnableOutbox(); #endregion var endpointInstance = await Endpoint.Start(endpointConfiguration) .ConfigureAwait(false); try { Console.WriteLine("Press any key to exit"); Console.ReadKey(); } finally { await endpointInstance.Stop() .ConfigureAwait(false); } }
public ReceiverDataContext GetDataContext(SynchronizedStorageSession storageSession) { if (context == null) { var dbConnection = storageSession.Session().Connection; context = new ReceiverDataContext(dbConnection); //Don't use transaction because connection is enlisted in the TransactionScope context.Database.UseTransaction(null); //Call SaveChanges before completing storage session storageSession.OnSaveChanges(x => context.SaveChangesAsync()); } return(context); }
static void Main() { Console.Title = "Samples.SQLNHibernateOutboxEF.Receiver"; using (var receiverDataContext = new ReceiverDataContext()) { receiverDataContext.Database.Initialize(true); } var hibernateConfig = new Configuration(); hibernateConfig.DataBaseIntegration( dataBaseIntegration: configurationProperties => { configurationProperties.ConnectionStringName = "NServiceBus/Persistence"; configurationProperties.Dialect <MsSql2012Dialect>(); }); hibernateConfig.SetProperty("default_schema", "receiver"); var busConfiguration = new BusConfiguration(); busConfiguration.UseSerialization <JsonSerializer>(); busConfiguration.EndpointName("Samples.SQLNHibernateOutboxEF.Receiver"); #region ReceiverConfiguration var transport = busConfiguration.UseTransport <SqlServerTransport>(); var connectionInfo = EndpointConnectionInfo.For("Samples.SQLNHibernateOutboxEF.Sender") .UseSchema("sender"); transport.UseSpecificConnectionInformation(connectionInfo); transport.DefaultSchema("receiver"); var persistence = busConfiguration.UsePersistence <NHibernatePersistence>(); persistence.RegisterManagedSessionInTheContainer(); busConfiguration.EnableOutbox(); #endregion using (Bus.Create(busConfiguration).Start()) { Console.WriteLine("Press any key to exit"); Console.ReadKey(); } }
static void Main() { Console.Title = "Samples.SQLNHibernateOutboxEF.Receiver"; using (ReceiverDataContext ctx = new ReceiverDataContext()) { ctx.Database.Initialize(true); } Configuration hibernateConfig = new Configuration(); hibernateConfig.DataBaseIntegration(x => { x.ConnectionStringName = "NServiceBus/Persistence"; x.Dialect<MsSql2012Dialect>(); }); hibernateConfig.SetProperty("default_schema", "receiver"); BusConfiguration busConfiguration = new BusConfiguration(); busConfiguration.UseSerialization<JsonSerializer>(); busConfiguration.EndpointName("Samples.SQLNHibernateOutboxEF.Receiver"); #region ReceiverConfiguration busConfiguration .UseTransport<SqlServerTransport>() .UseSpecificConnectionInformation( EndpointConnectionInfo.For("Samples.SQLNHibernateOutboxEF.Sender").UseSchema("sender")) .DefaultSchema("receiver"); busConfiguration .UsePersistence<NHibernatePersistence>() .RegisterManagedSessionInTheContainer(); busConfiguration.EnableOutbox(); #endregion using (Bus.Create(busConfiguration).Start()) { Console.WriteLine("Press any key to exit"); Console.ReadKey(); } }
public async Task Handle(OrderSubmitted message, IMessageHandlerContext context) { log.Info($"Order {message.OrderId} worth {message.Value} submitted"); var order = new Order { OrderId = message.OrderId, Value = message.Value }; var session = context.SynchronizedStorageSession.SqlPersistenceSession(); var dataContext = new ReceiverDataContext(session.Connection); dataContext.Database.UseTransaction(session.Transaction); dataContext.Orders.Add(order); await dataContext.SaveChangesAsync().ConfigureAwait(false); var orderAccepted = new OrderAccepted { OrderId = message.OrderId, }; await context.Reply(orderAccepted).ConfigureAwait(false); }
public CreateShipmentHandler(ReceiverDataContext dataContext) { this.dataContext = dataContext; }
static async Task Main() { const string tablePrefix = ""; Console.Title = "Samples.MultiTenant.Receiver"; var endpointConfiguration = new EndpointConfiguration("Samples.MultiTenant.Receiver"); endpointConfiguration.LimitMessageProcessingConcurrencyTo(1); endpointConfiguration.UseTransport <LearningTransport>(); #region DisablingOutboxCleanup var outboxSettings = endpointConfiguration.EnableOutbox(); outboxSettings.DisableCleanup(); #endregion var persistence = endpointConfiguration.UsePersistence <SqlPersistence>(); persistence.SqlDialect <SqlDialect.MsSqlServer>(); #region ConnectionFactory persistence.MultiTenantConnectionBuilder(tenantIdHeaderName: "tenant_id", buildConnectionFromTenantData: tenantId => { var connectionString = Connections.GetForTenant(tenantId); return(new SqlConnection(connectionString)); }); #endregion persistence.SubscriptionSettings().DisableCache(); persistence.TablePrefix(tablePrefix); var pipeline = endpointConfiguration.Pipeline; 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) .ConfigureAwait(false); using (var connection = new SqlConnection(Connections.TenantA)) using (var receiverDataContext = new ReceiverDataContext(connection)) { await receiverDataContext.Database.EnsureCreatedAsync(); } using (var connection = new SqlConnection(Connections.TenantB)) using (var receiverDataContext = new ReceiverDataContext(connection)) { await receiverDataContext.Database.EnsureCreatedAsync(); } var dialect = new SqlDialect.MsSqlServer(); var scriptDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "NServiceBus.Persistence.Sql", "MsSqlServer"); #region CreateSchema await ScriptRunner.Install(dialect, tablePrefix, () => new SqlConnection(Connections.TenantA), scriptDirectory, shouldInstallOutbox : true, shouldInstallSagas : true, shouldInstallSubscriptions : false, shouldInstallTimeouts : false); await ScriptRunner.Install(dialect, tablePrefix, () => new SqlConnection(Connections.TenantB), scriptDirectory, shouldInstallOutbox : true, shouldInstallSagas : true, shouldInstallSubscriptions : false, shouldInstallTimeouts : false); #endregion var endpointInstance = await startableEndpoint.Start() .ConfigureAwait(false); Console.WriteLine("Press any key to exit"); Console.ReadKey(); if (endpointInstance != null) { await endpointInstance.Stop() .ConfigureAwait(false); } }
public CreateOrderHandler(ReceiverDataContext dataContext) { this.dataContext = dataContext; }
static async Task Main() { const string tablePrefix = ""; Console.Title = "Samples.MultiTenant.Receiver"; var endpointConfiguration = new EndpointConfiguration("Samples.MultiTenant.Receiver"); endpointConfiguration.LimitMessageProcessingConcurrencyTo(1); endpointConfiguration.UseTransport <LearningTransport>(); endpointConfiguration.EnableOutbox(); var persistence = endpointConfiguration.UsePersistence <SqlPersistence>(); persistence.SqlDialect <SqlDialect.MsSqlServer>(); #region ConnectionFactory persistence.ConnectionBuilder(MultiTenantConnectionFactory.GetConnection); #endregion persistence.SubscriptionSettings().DisableCache(); persistence.TablePrefix(tablePrefix); var pipeline = endpointConfiguration.Pipeline; #region ExtractTenantConnectionStringBehavior pipeline.Register( behavior: typeof(ExtractTenantConnectionStringBehavior), description: "Extracts tenant connection string based on tenant ID header."); #endregion 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) .ConfigureAwait(false); using (var connection = new SqlConnection(Connections.TenantA)) using (var receiverDataContext = new ReceiverDataContext(connection)) { await receiverDataContext.Database.EnsureCreatedAsync(); } using (var connection = new SqlConnection(Connections.TenantB)) using (var receiverDataContext = new ReceiverDataContext(connection)) { await receiverDataContext.Database.EnsureCreatedAsync(); } var dialect = new SqlDialect.MsSqlServer(); var scriptDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "NServiceBus.Persistence.Sql", "MsSqlServer"); #region CreateSchema await ScriptRunner.Install(dialect, tablePrefix, () => new SqlConnection(Connections.TenantA), scriptDirectory, shouldInstallOutbox : false, shouldInstallSagas : true, shouldInstallSubscriptions : false, shouldInstallTimeouts : false); await ScriptRunner.Install(dialect, tablePrefix, () => new SqlConnection(Connections.TenantB), scriptDirectory, shouldInstallOutbox : false, shouldInstallSagas : true, shouldInstallSubscriptions : false, shouldInstallTimeouts : false); await ScriptRunner.Install(dialect, tablePrefix, () => new SqlConnection(Connections.Shared), scriptDirectory, shouldInstallOutbox : true, shouldInstallSagas : false, shouldInstallSubscriptions : false, shouldInstallTimeouts : true); #endregion #region Synonyms var sql = @" if exists (select * from sys.synonyms where [name] = 'OutboxData') return; create synonym OutboxData FOR [SqlMultiTenantReceiver].[dbo].[OutboxData]"; SqlHelper.ExecuteSql(Connections.TenantA, sql); SqlHelper.ExecuteSql(Connections.TenantB, sql); #endregion var endpointInstance = await startableEndpoint.Start() .ConfigureAwait(false); Console.WriteLine("Press any key to exit"); Console.ReadKey(); if (endpointInstance != null) { await endpointInstance.Stop() .ConfigureAwait(false); } }