views:

217

answers:

2

I would like to apply a custom attribute to some methods that indicates they should be handled as a transaction. In general, I know how to create custom attributes by inheriting from System.Attribute, but I don't know how to do what I need.

My goal is something like this:

[TransactionalMethod()]
public void SaveData(object someObject)
{
    // ... maybe some processing here
    // ... then the object gets saved to a database
    someObject.Save();
}

The TransactionalMethod() attribute would make the method behave as if it were wrapped in a TransactionScope...

 try 
 {
     using(TransactionScope scope = new TransactionScope())
     {
         SaveData(someObject);
         scope.Complete();
     }
 }
 catch 
 {
     // handle the exception here
 }

If the SaveData() method throws an exception then we would fall outside the Using and the scope.Complete would not be called.

I don't want to have to find every instance where SaveData() is called and manually add the code Using statement around it. How could I make an attribute that causes this behavior?

+5  A: 

Basically you want Aspect-Oriented Programming (AOP).

Have a look at PostSharp - it can handle this well. There are other options too, but I haven't used them.

Jon Skeet
Curse you and your fast posting, Jon Skeet!!! :D I had almost exactly the same post; I was looking up the link to PostSharp, and there you are, already done.
Randolpho
There are a few URLs I know without looking them up, and postsharp.org is one of them :)
Jon Skeet
+2  A: 

Aspect.NET is another project which serves the same purpose