Skip to content

Instantly share code, notes, and snippets.

@ramonsmits
Created June 18, 2015 19:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ramonsmits/f7d20dbfd5335e6b1afc to your computer and use it in GitHub Desktop.
Save ramonsmits/f7d20dbfd5335e6b1afc to your computer and use it in GitHub Desktop.
NServiceBus behavior to share persistence database connection
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