This week I’ve been working on a brownfield Castle-powered WCF service that was creating a separate NHibernate session on every call to a repository object.

Abusing NHibernate like this was playing all sorts of hell for our app (e.g. TransientObjectExceptions), and prevented us from using transactions that matched with a logical unit of work, so I set about refactoring it.

Goals

  • One session per WCF operation
  • One transaction per WCF operation
  • Direct access to ISession in my services
  • Rely on Castle facilities as much as possible
  • No hand-rolled code to plug everything together

There are a plethora of blog posts out there to tackle this problem, but most of them require lots of hand-rolled code. Here are a couple of good ones — they both create a custom WCF context extension to hold the NHibernate session, and initialize/dispose it via WCF behaviours:

These work well, but actually, there is a much simpler way that only requires the NHibernate and WCF Integration facilities.

Option one: manual Session.BeginTransaction() / Commit()

The easiest way to do this is to register NHibernate’s ISession in the container, with a per WCF operation lifestyle:

windsor.AddFacility<WcfFacility>();
windsor.AddFacility("nhibernate", new NHibernateFacility(...));

windsor.Register(
    Component.For<ISession>().LifeStyle.PerWcfOperation()
        .UsingFactoryMethod(x => windsor.Resolve<ISessionManager>().OpenSession()),
    Component.For<MyWcfService>().LifeStyle.PerWcfOperation()));

If you want a transaction, you have to manually open and commit it. (You don’t need to worry about anything else because NHibernate’s ITransaction rolls back automatically on dispose):

[ServiceBehavior]
public class MyWcfService : IMyWcfService
{
    readonly ISession session;

    public MyWcfService(ISession session)
    {
        this.session = session;
    }

    public void DoSomething()
    {
        using (var tx = session.BeginTransaction())
        {
            // do stuff
            session.Save(...);

            tx.Commit();
        }
    }
}

(Note of course we are using WindsorServiceHostFactory so Castle acts as a factory for our WCF services. And disclaimer: I am not advocating putting data access and persistence directly in your WCF services here; in reality ISession would more likely be injected into query objects and repositories each with a per WCF operation lifestyle (you can use this to check for lifestyle conflicts). It is just an example for this post.)

Anyway, that’s pretty good, and allows a great deal of control. But developers must remember to use a transaction, or remember to flush the session, or else changes won’t be saved to the database. How about some help from Castle here?

Option two: automatic [Transaction] wrapper

Castle’s Automatic Transaction Facility allows you to decorate methods as [Transaction] and it will automatically wrap a transaction around it. IoC registration becomes simpler:

windsor.AddFacility<WcfFacility>();
windsor.AddFacility("nhibernate", new NHibernateFacility(...));
windsor.AddFacility<TransactionFacility>();

windsor.Register(
    Component.For<MyWcfService>().LifeStyle.PerWcfOperation()));

And using it:

[ServiceBehavior, Transactional]
public class MyWcfService : IMyWcfService
{
    readonly ISessionManager sessionManager;

    public MyWcfService(ISessionManager sessionManager)
    {
        this.sessionManager = sessionManager;
    }

    [Transaction]
    public virtual void DoSomething()
    {
        // do stuff
        sessionManager.OpenSession.Save(...);
    }
}

What are we doing here?

  • We decorate methods with [Transaction] (remember to make them virtual!) instead of manually opening/closing transactions. I put this attribute on the service method itself, but you could put it anywhere — for example on a CQRS command handler, or domain event handler etc. Of course this requires that the class with the [Transactional] attribute is instantiated via Windsor so it can proxy it.
  • Nothing in the NHibernateFacility needs to be registered per WCF operation lifestyle. I believe this is because NHibernateFacility uses the CallContextSessionStore by default, which in a WCF service happens to be scoped to the duration of a WCF operation.
  • Callers must not dispose the session — that will be done by castle after the transaction is commited. To discourage this I am using it as a method chain — sessionManager.OpenSession().Save() etc.
  • Inject ISessionManager, not ISession. The reason for this is related to transactions: NHibernateFacility must construct the session after the transaction is opened, otherwise it won’t know to enlist it. (NHibernateFacility knows about ITransactionManger, but ITransactionManager doesn’t know about NHibernateFacility). If your service depends on ISession, Castle will construct the session when MyWcfService and its dependencies are resolved (time of object creation) before the transaction has started (time of method dispatch). Using ISessionManager allows you to lazily construct the session after the transaction is opened.
  • In fact, for this reason, ISession is not registered in the container at all — it is only accessible via ISessionManager (which is automatically registered by the NHibernate Integration Facility).

This gives us an NHibernate session per WCF operation, with automatic transaction support, without the need for any additional code.

August 17th, 2010 | 2 Comments

Lately I have become a big opponent of a popular anti-pattern: people insisting on splitting up their application tiers/layers into 5-10 separate Visual Studio projects and adding references between them. Double that number of projects if you want corresponding unit test project for each layer.

In fact, removing them has become one of the first steps I take when inheriting a legacy code base. If I were writing a book on refactoring Visual Studio solutions, I would call it Merge redundant assemblies. Here’s a diagram:

You don’t need to split your code across 50 gazillion projects. Next time you think of creating a new project in your solution, please remember the following:

  • Visual Studio projects are for outputing assemblies. Namespaces are for organising code.
  • Assemblies only need to be split if your deployment scenario demands it. Putting a client API library into a separate assembly makes sense because the same API assembly may be used between many apps, or in different App Domains. Deploying your domain model or data layer into a separate assembly does not make sense, unless other apps need them too.
  • Each additional project slows down your build. A giant project with hundreds of classes will compile faster than a smaller number of classes split amongst multiple projects.
  • Crossing assembly boundaries hurts runtime performance. Your app will start up slower, the ability to perform inlining and OS optimization is reduced, and additional security overhead is enforced between assemblies. Assemblies are supposed to be big and heavy; loading lots of little one goes against the CLR.
  • You don’t need one test project for each assembly. One giant tests project is normally fine. The only case I have seen where it made sense to have separate test projects was for a client API which duplicated many of the server internal class names and we wanted to avoid overlap/namespace pollution.
  • Common sense should be used to enforce one-way dependencies. Not assembly references.

Patrick Smacchia has a good list of valid/invalid use cases where separate assemblies are appropriate here.

August 16th, 2010 | 3 Comments

Here’s a super quick little powershell snippet to strip regions out of all C# files in a directory tree. Useful for legacy code where people hide long blocks in regions rather than encapsulate it into smaller methods/objects.

dir -recurse -filter *.cs $src | foreach ($_) {
    $file = $_.fullname
    echo $file
    (get-content $file) | where {$_ -notmatch "^.*\#(end)?region.*$" } | out-file $file
}

Run this in your solution folder and support the movement against C# regions!

August 12th, 2010 | 4 Comments

Just spotted this in a project I’m working on:

public static string GetExceptionAsString(this Exception exception)
{
	return string.Format("Exception message: {0}. " + Environment.NewLine +
 		"StackTrace: {1}. {2}", exception.Message, exception.StackTrace,
		GetAnyInnerExceptionsAsString(exception));
}

Writing code like this should be a shooting offense.

But wait, there’s more! Check out its usage:

try
{
	...
}
catch (Exception ex)
{
	log.InfoFormat("Error occured:{0}.", ex.GetExceptionAsString());
}

Agh!

Code like this demonstrates a complete misunderstanding of CLR exception basics — inner exceptions and formatting — and also log4net. All that hand-rolled formatting could simply be replaced with:

  • GetExceptionAsString() -> Exception.ToString()
  • ILog.InfoFormat(format, args) -> ILog.Info(message, exception)
June 25th, 2010 | 4 Comments

Prism’s event aggregator is great for decoupling UI state changes when UI events occur, but sometimes you need to perform some larger, long-running task on a background thread — uploading a file, for example.

Here’s a quick example of an encapsulated event handler listening off the Prism event bus, and using Windsor’s IStartable facility to handle event subscription:

public class TradeCancelledEventHandler : ICompositePresentationEventHandler, IStartable
{
    private readonly IEventAggregator eventAggregator;

    protected TradeCancelledEventHandler(IEventAggregator eventAggregator)
    {
        if (eventAggregator == null)
            throw new ArgumentNullException("eventAggregator");

        this.eventAggregator = eventAggregator;
    }

    public void Start()
    {
        // Register to receive events on the background thread
        eventAggregator
            .GetEvent<TradeCancelledEvent>()
            .Subscribe(Handle, ThreadOption.BackgroundThread);
    }

    public void Stop()
    {
        eventAggregator
            .GetEvent<TradeCancelledEvent>()
            .Unsubscribe(Handle);
    }

    void Handle(TradeCancelledEventArgs eventArgs)
    {
        // ... do stuff with the event
    }
}

Each event handler is effectively a little service running in the container. Note ICompositePresentationEventHandler is a simple role interface that allows us to register them all at once in the IoC container:

public interface ICompositePresentationEventHandler {}

...

container.AddFacility<StartableFacility>();

// Register event handlers in container
container.Register(
    AllTypes
        .Of<ICompositePresentationEventHandler>()
        .FromAssembly(Assembly.GetExecutingAssembly()));
June 24th, 2010 | No Comments Yet