This project is read-only.

Threading issues with WebApi + Autofac + TransactionScope

Topics: Web Api
Feb 13, 2012 at 10:25 PM

Hi All..

Im sure this is an edge case, but I am having problems implementing a transaction-per-request model.

I have implemented part of the Orchard Framework, and put a WebApi module within it. Everything work great until dispose is called on the TransactionScope.. the error I recieve is.. A TransactionScope must be disposed on the same thread

The problem I think is that the CreateInstance delegate is not being called on the same instance, which means that ILifetimeScope is created on one instance, CreateInstance is then called which in turn creates a TransactionScope, and then dispose ILifetimeScope is called on the original thead which obviously causes that issue...

This code creates the context..

        private readonly IItvServices _itvServices;

        public VideoEntriesWebApiConfiguration(IItvServices itvServices) {
            _itvServices = itvServices;

            CreateInstance = (serviceType, context, request) => {
                IVideoEntriesResource videoEntriesResource;
                _itvServices.WorkContext.TryResolve(out videoEntriesResource);
                return videoEntriesResource;
Inside of the Post event of IVideoEntriesResource TransactionScope Demand is called.

Any ideas chaps? I can provide more code and context if required.