我想将自定义属性应用于某些表明它们应作为事务处理的方法.一般来说,我知道如何通过继承System.Attribute来创建自定义属性,但我不知道如何做我需要的.
我的目标是这样的:
[TransactionalMethod()]
public void SaveData(object someObject)
{
// ... maybe some processing here
// ... then the object gets saved to a database
someObject.Save();
}
Run Code Online (Sandbox Code Playgroud)
TransactionalMethod()属性将使该方法的行为就像它包装在TransactionScope中一样......
try
{
using(TransactionScope scope = new TransactionScope())
{
SaveData(someObject);
scope.Complete();
}
}
catch
{
// handle the exception here
}
Run Code Online (Sandbox Code Playgroud)
如果SaveData()方法抛出一个异常,那么我们就会落在Using和scope.Complete之外.
我不想找到调用SaveData()的每个实例,并手动添加代码使用它周围的语句.我怎样才能创建导致此行为的属性?