Using NHibernate Session Per Request with WCF Windsor Integration
Okay, this is a quickie, but here is how you can do it, you need to register a UnitOfWorkEndPointBehavior implementation on the container, and make sure that your WCF services are used through the WindsorServiceHost. That is all. What is the UnitOfWorkEndPointBehavior, you ask, here it is:
public class UnitOfworkEndPointBehavior : IEndpointBehavior
{
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
foreach (DispatchOperation operation in endpointDispatcher.DispatchRuntime.Operations)
{
operation.CallContextInitializers.Add(new UnitOfWorkCallContextInitializer());
}
}
}
public class UnitOfWorkCallContextInitializer : ICallContextInitializer
{
public object BeforeInvoke(InstanceContext instanceContext, IClientChannel channel, Message message)
{
ISession session = factory.OpenSession();
OperationContext.Items["NHibernate_Session"] = session;
return session;
}
public void AfterInvoke(object correlationState)
{
((IDisposable)correlationState).Dispose();
}
}
public static class UnitOfWork
{
public static ISession Current { get { return (ISession )OperationContext.Items["NHibernate_Session"]; }
}