Deploying a Unit of Work in a WCF Service Using Autofac

How can I implement a unit of work pattern in a WCF service using Autofac?

Deploying the same instance for each call (or in terms of Autofac LifetimeScope) of the working interface module to my services and repositories is easily done by integrating Autocac wcf - what I get is a way to fix the unit of work change when returning a WCF service call explicitly ONLY if there were no exceptions.

I saw Using Endpoint Custom Behavior with WCF and Autofac , basically, as I started, but this does not apply to exceptions.

I currently have an IOperationInvoker which runs a unit of work in Invoke and only captures it if there are no exceptions. The problem with this approach is that I need to allow an instance of my unit of work inside the Invoke method, which gives me a different instance than the one that was introduced into my services and repositories using AutofacInstanceProvider .

+6
source share
1 answer

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.

+1
source

Source: https://habr.com/ru/post/912293/


All Articles