How to handle transactions in ASP.NET MVC3

I got annoyed about having to repeat the transaction handling in every POST method of my controllers. First of all: I don’t want to have to take the unit of work in the constructor of each controller, since that implicitly says that all/most methods uses transactions. And I do not want to have to resolve a factory, since that says that all methods might use transactions. Finally using a singleton is the worst of solutions.

Before

The problem wasn’t that hard to solve thanks to the flexibility of ASP.NET MVC3. But let’s start by looking at a typical post method:

[HttpPost]
public virtual ActionResult Create(CreateModel model)
{
	if (!ModelState.IsValid)
		return View(model);

	var instruction = new Instruction(CurrentUser);
	Mapper.Map(model, instruction);

	using (var uow = _unitOfWorkFactory.Create())
	{
		_repository.Save(instruction);
		
		uow.SaveChanges();
	}
	
	return RedirectToAction("Details", new {id = instruction.Id});
}

After

What I did was to create a new action filter called TransactionalAttribute. It checks if the model state is valid and that no exceptions have been thrown. It uses the DependencyResolver to find a IUnitOfWork implementation if everything checks out OK. Since this is done in an action filter, the transaction will not be created unless it’s actually required. All you have to do is to register the UoW factory in your IoC container and tag your action:

[HttpPost, Transactional]
public virtual ActionResult Create(CreateModel model)
{
	if (!ModelState.IsValid)
		return View(model);

	var instruction = new Instruction(CurrentUser);
	Mapper.Map(model, instruction);
	_repository.Save(instruction);
	
	return RedirectToAction("Details", new {id = instruction.Id});
}

There is a small catch: You must add an error to the ModelState if you catch exceptions in your class. The transaction will otherwise get committed.

[HttpPost, Transactional]
public virtual ActionResult Create(CreateModel model)
{
	if (!ModelState.IsValid)
		return View(model);

	try
	{
		model.Category = model.Category ?? "Allmänt";

		var instruction = new Instruction(CurrentUser);
		Mapper.Map(model, instruction);
		_repository.Save(instruction);
		
		return RedirectToAction("Details", new {id = instruction.Id});
	}
	catch (Exception err)
	{
		// Adds an error to prevent commit.
		ModelState.AddModelError("", err.Message);
		Logger.Error("Failed to save instruction for app " + CurrentApplication, err);
		return View(model);
	}
}

Implementation

The attribute itself looks like this:

public class TransactionalAttribute : ActionFilterAttribute
{
	private IUnitOfWork _unitOfWork;

	public override void OnActionExecuting(ActionExecutingContext filterContext)
	{
		if (filterContext.Controller.ViewData.ModelState.IsValid && filterContext.HttpContext.Error == null)
			_unitOfWork = DependencyResolver.Current.GetService<IUnitOfWork>();

		base.OnActionExecuting(filterContext);
	}

	public override void OnActionExecuted(ActionExecutedContext filterContext)
	{
		if (filterContext.Controller.ViewData.ModelState.IsValid && filterContext.HttpContext.Error == null && _unitOfWork != null)
			_unitOfWork.SaveChanges();

		base.OnActionExecuted(filterContext);
	}
}

Simple, but effective! :)

Extras

The actual unit of work implementation depends on which kind of data layer you are using. You can use the following code snippet if you are using nhibernate and have successfully registered the ISession in your container:

public class NhibernateUnitOfWork : IUnitOfWork
{
	private readonly ISession _session;
	private ITransaction _transaction;

	public NhibernateUnitOfWork(ISession session)
	{
		_session = session;
		_transaction = session.BeginTransaction();
	}

	public void Dispose()
	{
		if (_transaction == null)
			return;

		if (!_transaction.WasCommitted)
			_transaction.Rollback();

		_transaction.Dispose();
		_transaction = null;
	}

	public void SaveChanges()
	{
		_transaction.Commit();
	}

}

The Unit of work interface is really simple:

public interface IUnitOfWork : IDisposable
{
	void SaveChanges();
}

  • http://www.cuttingedge.it/blogs/steven Steven

    IMO the controller should not know anything about handling transactions and you still have to repeat that Transactional attribute all over the place.Seems to me you’re not SOLID and DRY with this approach. Looks like you’re missing an abstraction.

    A great solution is to model all business logic inside (generic) command handlers. This allows you to define a single decorator that can be wrapped around every handler (or conditionally if you wish), without the presentation layer to know anything about this. With a good DI container, registering such a decorator is just a one-liner ;-)

    Here’s an example of a command handler implementation: http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=91

    Cheers

    • http://www.gauffin.org jgauffin

      I don’t agree. For instance: Only the original caller knows if several services should share an transaction or not. Each individual service cannot decide that.

      Commands is a nice way to handle that. But what if you want to include several commands in the same transaction? Again, the caller should decide that.

      That’s why I prefer to control the transactions directly in the controllers. The code is clean and easy to follow.

      (I have to add support for AOP as soon as I get a chance ;)

    • Craig

      Yes, I do it similar to you. Much nicer.

  • http://www.cuttingedge.it/blogs/steven Steven

    Wouldn’t it be nice to be able leave the notion of transactions completely out of the presentation layer?

    I see a command as a use case. There will be a one to one mapping between a command and a use case. This is very nice way to approach things, because this way there is also a one to one mapping between use case documentation and code. When you use this as architectural rule, you will never see a Controller execute multiple commands in the same action method, because one user actual cannot trigger multiple use cases with a single click (because this is the definition of a use case). A big use case might consist of multiple smaller sub use cases, and a command might therefore call other (sub) commands . When you do this, you can leave this out of the controller, and it allows you to let the controller just do presentation/controller stuff. This way a Controller action method will only have a single handler.Handle(command) call. When the controller is only allowed to call one handler, you can leave it up completely to the business layer or infrastructure to decide how to handle transactional support. As I’ve shown in the article, it’s pretty easy to handle transactional support in decorators, and it won’t be much harder when dealing with sub commands

    btw, I didn’t want to mock the Griffin container, but the wink was because I plugged Simple Injector :-p. Although I must say that even some of the big DI containers (such as Unity and Castle Windsor), make registering generic decorators extremely difficult (considering the unanswered questions on Stackoverflow about this). The only two containers I know that have great support for this are Autofac and Simple Injector.

    Instead of adding such a feature to Griffin.Container, what do I have to do to get you on the dark side and go for the Simple Injector?

    • http://www.gauffin.org jgauffin

      the problem is still there if you start talking about commands and sub commands. The sub commands might be “real” commands to, which means that they either need to use the parents transaction or create a new one.

      imho it’s much more elegant to just decorate the post actions in MVC3.

      I do prefer to use proper domain models in combination of services and repositories instead of commands. At least in for the applications which I build (small-medium sized). Commands is a lot better for large applications since it makes it easy to refactor the application without hassle (as all dependencies are to commands).

      As for Griffin.Container. I’ve spent less than a week on it. It’s of course still missing features. I don’t care if you mock it or not :) Getting decorators into the container won’t be hard. I’ll just use Castle proxy for that.

  • http://www.cuttingedge.it/blogs/steven Steven

    “Commands is a lot better for large applications”

    This is of course open to discussion, but I’ve had a lot of success with implementing the command/handler pattern in small and medium sized applications. There isn’t much overhead (although its usage is questionable when dealing with a REAL CRUD app). However, it IS a mental shift for the developers, just as SOLID itself is a real mind shift. So I think it’s not the size of the project that should influence whether you use this pattern; it is the experience of the developers who need to understand this pattern. You can’t just walk in as a consultant, explain this pattern on a single afternoon and go home, and expect all developers to correctly implement it. But that said, do you really ever know when an application will grow “large”? I’ve seen many projects were developers and management though the project would never be big. But more than often, a few years later, they ended up working with a dozen developers on a big messy code base. Although it will not solve all your problems, the command/pattern (when doing right of course), but since it is SOLID to its core, it will solve a lot of future problems for you, that you will even be able to predict. And it does that, without adding much infrastructure. Take for instance when you need to make business logic accessible through WCF services or need to be able to queue commands to a Windows Service. You will be able to do this without going through your whole application to make it ready for this. Just some infrastructure code will do the trick.

    “Getting decorators into the container won’t be hard. I’ll just use Castle proxy for that.”

    IMO you should stay away from proxy generation for implementing decorator support for two reasons. First of all, if you want great performance (which I believe you do), you just want to decorate, not proxy. Even though Castle Proxy generates code, there is still some reflection/indirection going on. By using decorators as in the decorator design pattern, you won’t have this issue. Besides, for your users, writing a decorator is much easier than writing an interceptor, and interceptors are framework specific. Not a big deal, but I must admit that since being SOLID (and having a container with great decorator support), I never needed to do anything with interception. In my opinion this is what’s bad about Unity. It only allows you to do this through interception (or at least, there is no easy way to do this). This is what I like about Autofac, and of course, Simple Injector.

    However, adding decorator support without proxy generation, is probably a lot harder – for you as a framework developer. Before Simple Injector supported this out-of-the-box, I published an extension method for this on CodePlex. It took me less than 30 minutes to write this. So with the right extension points in place it didn’t take long to do, but… the corner cases are far from trivial when dealing with generic types. Generic type constraints, generic type ‘reordering’, and nested generic types make it pretty nasty to implement. But if you go this route, just take a look at the Simpel Injector source code. There are two classes that do this behavior. You should be done in a second ;-)

    “don’t care if you mock it or not”

    But I seriously don’t want to mock you. I like what you are doing; I did the same :-). And as you noticed, I like to talk about these subjects :-)
    The best tip I can give you on writing your own container is: Read Mark Seemann’s book. Really. You can’t imagine how much this will help on hour understanding of DI (even if you already know it quite well).

    • http://www.gauffin.org jgauffin

      “Command pattern”

      Good for you. =) The deadlock retry command decorator was quite nice. Good job. that isn’t as easy using a “regular” architecture.

      The biggest problem with command based architectures is that it can quickly get out of hand when you start chaining commands. It can lead to a mess which is quite hard to follow. The “traditional” approach with services/repositories/domain models give you a more linear approach.

      It’s just two ways of designing the application. The important thing is not which one you use, but that you know of both and the pros/cons that each architecture have.

      I’m going to try a command based architecture from some small project when I get the time =)

      “Decorators”

      Yeah, we are both talking of decorator pattern. I’ve implemented decorators now.

      And got a separate package using Castle Proxy for that (i.e. castle is not mandatory to implement decorators). There is a sample decorator which logs all exceptions (+ method + all arguments) for all types registered in the container.

      Will publish it in the weekend.

      “Mocking”

      Come one. Admit it. You do mock me. Don’t be scared to admit it.

  • http://www.cuttingedge.it/blogs/steven Steven

    “The biggest problem with command based architectures is that it can quickly get out of hand when you start chaining commands.”

    I agree with that. You have to think twice before you start nesting them, but of course, but I never of course said that there won’t be any design challenges anymore when you start using command based architecture :-). Don’t forget that you can use your ‘linear’ approach easily inside a single command.

    “The important thing is [...] that you know of both and the pros/cons that each architecture have.”

    Amen!!

    “I’m going to try a command based architecture”

    That’s the spirit! :-D

    “Come one. Admit it. You do mock me”

    Okay, you got me. But only because I’m afraid of the competition ;-)

  • http://www.dotnetjalps.com/ Jalpesh Vadgama

    Nice job!!