Created
June 18, 2015 19:42
-
-
Save ramonsmits/f7d20dbfd5335e6b1afc to your computer and use it in GitHub Desktop.
NServiceBus behavior to share persistence database connection
This file contains 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; | |
using System.Data; | |
using System.Diagnostics; | |
using NServiceBus; | |
using NServiceBus.Persistence.NHibernate; | |
using NServiceBus.Pipeline; | |
using NServiceBus.Pipeline.Contexts; | |
class MyContextBehaviorRegistration : INeedInitialization | |
{ | |
public void Customize(BusConfiguration busConfiguration) | |
{ | |
busConfiguration.RegisterComponents(r => r.ConfigureComponent<MyContext>(DependencyLifecycle.InstancePerCall)); | |
busConfiguration.RegisterComponents(r => r.ConfigureComponent<IDbConnection>(b => b.Build<NHibernateStorageContext>().Connection, DependencyLifecycle.InstancePerCall)); | |
// Register the new step in the pipeline | |
busConfiguration.Pipeline.Register<MyContextBehavior.Registration>(); | |
} | |
} | |
class MyContextBehavior : IBehavior<IncomingContext> | |
{ | |
public void Invoke(IncomingContext context, Action next) | |
{ | |
var ctx = context.Builder.Build<MyContext>(); | |
next(); | |
ctx.SaveChanges(); | |
} | |
internal class Registration : RegisterStep | |
{ | |
public Registration() | |
: base(typeof(MyContextBehavior).Name, typeof(MyContextBehavior), "Database context behavior yo!") | |
{ | |
InsertAfter(WellKnownStep.MutateIncomingMessages); | |
} | |
} | |
} | |
class MyContext | |
{ | |
public MyContext(IDbConnection connection) | |
{ | |
Console.WriteLine("Constructor | IDbConnection"); | |
Debug.Assert(connection != null, "No shared connection injected."); | |
// Pass it to the base class here or via the constructor | |
} | |
public void SaveChanges() | |
{ | |
Console.WriteLine("SaveChanges"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment