Created
July 11, 2018 19:13
-
-
Save ramonsmits/8e63002f8caa6dc4fda61f9397035b44 to your computer and use it in GitHub Desktop.
NServiceBus - Use different database catalog on same database server instance with connection sharing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System.Data.Entity; | |
| using System.Threading.Tasks; | |
| using NServiceBus; | |
| public class UpdateDataInDifferentCatalogHandler | |
| : IHandleMessages<CompleteOrder> | |
| { | |
| public async Task Handle(MyMessage message, IMessageHandlerContext context) | |
| { | |
| var sharedSession = context.SynchronizedStorageSession.SqlPersistenceSession(); | |
| var connection = sharedSession.Connection; | |
| var dbName = connection.Database; // Store current catalog | |
| connection.ChangeDatabase("Sales"); | |
| try | |
| { | |
| using (var dbContext = new MyDbContext(connection)) | |
| { | |
| dbContext.Database.UseTransaction(sharedSession.Transaction); | |
| // Do your usual operations on your DbContext | |
| await dataContext.SaveChangesAsync() | |
| .ConfigureAwait(false); | |
| } | |
| } | |
| finally | |
| { | |
| sharedSession.ChangeDatabase(dbName); // Revert to previous catalog | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment