Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control method behavior via an attribute?

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?

like image 980
Sailing Judo Avatar asked Apr 07 '09 15:04

Sailing Judo


2 Answers

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.

like image 92
Jon Skeet Avatar answered Nov 08 '22 02:11

Jon Skeet


Aspect.NET is another project which serves the same purpose

like image 32
user89219 Avatar answered Nov 08 '22 01:11

user89219