Bradley Boveinis found a solution to this problem. We have not tested it completely, but it seems to work:
public class UnitOfWorkAwareOperationInvoker : IOperationInvoker { private readonly IOperationInvoker _baseInvoker; public UnitOfWorkAwareOperationInvoker(IOperationInvoker baseInvoker) { _baseInvoker = baseInvoker; } public object[] AllocateInputs() { return _baseInvoker.AllocateInputs(); } public object Invoke(object instance, object[] inputs, out object[] outputs) { var result = _baseInvoker.Invoke(instance, inputs, out outputs); var context = OperationContext.Current.InstanceContext.Extensions.Find<AutofacInstanceContext>(); try { context.Resolve<IUnitOfWork>().Save(); } catch (Exception ex) { var message = Message.CreateMessage(MessageVersion.Default, string.Empty); new ElmahErrorHandler().ProvideFault(ex, null, ref message); throw; } return result; } public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state) { return _baseInvoker.InvokeBegin(instance, inputs, callback, state); } public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result) { return _baseInvoker.InvokeEnd(instance, out outputs, result); } public bool IsSynchronous { get { return _baseInvoker.IsSynchronous; } } }
The key is in the following line:
OperationContext.Current.InstanceContext.Extensions.Find<AutofacInstanceContext>();
This captures UoW from the surrounding / current / contextual LifetimeScope.
source share