This post describes how to achieve database transaction, on a request level, with Autofac DI and ASP.NET WebApi.

Sometimes there is a need to share transaction between two different ORMs which uses the same database – in my case Entity Framework and Dapper. It will allow you to be sure that changes, made by two different tools, will be done completely or not. To realize such scenario you can use TransactionScope class. It provides an option to create a transaction, which will be used by SQL connection.

First, you need to create an instance of Autofac interface IAutofacActionFilter – filter which is run before and after every HTTP action:

The filter creates transaction every executed action and completes it when there is no error. These posts (12) describe why, by default, you should create TransactionScope with above options.

Then you need to register your filter during the creation of Autofac ContainerBuilder – typically when the application is being started.

The filter is registered with an InstancePerRequest option, which forces to create filter only once per request. Without it, for OnActionExecutingAsync and OnActionExecutedAsync, Autofac creates 2 instances of the filter.

In most cases you want to register the filter for all controllers, that’s why its registered against ApiController. But you can implement more sophisticated logic there, even with some reflection included.

PS. Here you find how to achieve database transaction on a command level.