Skip to content

Instantly share code, notes, and snippets.

@cairey
Created October 19, 2012 09:12
Show Gist options
  • Save cairey/3917101 to your computer and use it in GitHub Desktop.
Save cairey/3917101 to your computer and use it in GitHub Desktop.
WCF Unit of work Behavior
public class UnitOfWorkBehaviorAttribute : Attribute, IContractBehavior, IContractBehaviorAttribute
{
public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
{ }
public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
{
foreach(var operation in dispatchRuntime.EndpointDispatcher.DispatchRuntime.Operations)
{
operation.CallContextInitializers.Add(new PCMUnitOfWorkCallContextInitializer());
}
}
public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{}
public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{}
public Type TargetContract
{
get { return null; }
}
}
public class PCMUnitOfWorkCallContextInitializer : ICallContextInitializer
{
public object BeforeInvoke(InstanceContext instanceContext, IClientChannel channel, Message message)
{
var unitOfWork = ObjectFactory.Container.Resolve<IUnitOfWork>();
if(unitOfWork.IsNotNull())
unitOfWork.Start();
return unitOfWork;
}
public void AfterInvoke(object correlationState)
{
var unitOfWork = correlationState as IUnitOfWork;
if(unitOfWork.IsNotNull())
unitOfWork.End();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment