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?
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.
Aspect.NET is another project which serves the same purpose
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With