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?