如何通过一个属性控制方法的行为? [英] How to control method behavior via an attribute?
问题描述
我想自定义属性应用到一些方法,指出它们应该被处理为交易。在一般情况下,我知道如何通过从System.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.
我的目标是这样的:
[TransactionalMethod()]
public void SaveData(object someObject)
{
// ... maybe some processing here
// ... then the object gets saved to a database
someObject.Save();
}
在TransactionalMethod()属性将使的行为,就好像它被包裹在该方法中的TransactionScope ...
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
}
如果在保存数据()方法抛出一个异常,那么我们就属于使用和scope.Complete就不叫外面。
If the SaveData() method throws an exception then we would fall outside the Using and the scope.Complete would not be called.
我不希望要找到每一个地方保存数据()被调用实例和手动添加code用它周围的语句。我如何才能让一个属性,导致这种行为?
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?
推荐答案
Aspect.NET是另外一个项目,有异曲同工之妙。
Aspect.NET is another project which serves the same purpose
这篇关于如何通过一个属性控制方法的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!