Non-database usage for System.Transactions

I recently ran into a case where I wanted to validate a collection of objects that, in turn, contained a collection of objects, then change an attribute of each item in both the parent and child collections. The goal was to do this all in a single pass (for speed) but the problem was that I had to know that all objects in the collection were valid before I wanted to set the value.
This model lends itself to the Unit of Work pattern from Martin Fowler‘s book, Patterns of Enterprise Application Architecture, but is also very similar to a simple database transaction in ADO.Net. New in .Net 2.0 is the System.Transactions Namespace that allows you to, cleanly, code transactions into your objects. An article by Sahil Malik is a fantastic example of how to implement your own resource manager to have a transaction in something other than a database connection (which seems to be what many of the examples out there illustrate).
I ran some unit tests to confirm that it was working appropriately in my situation and the green light went on! Now the method runs in a single pass and rolls back the member variable value if an exception is thrown at any point during validation of any of the individual collection items, parent or child. Fast and effective. I love it!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s