I would like to dynamically get the value of the attribute on method, which could be anywhere in the calling hierarchy.
Now I have found the solution using StackTrace's FrameCount and GetFrame. But it's not dynamic
Rollback.cs
namespace AnotationTest
{
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
class RollbackAttribute: Attribute
{
public Guid RollbackGuid { get; set; }
public RollbackAttribute()
{
RollbackGuid = Guid.NewGuid();
}
}
}
Program.cs
class Program
{
static void Main(string[] args)
{
Test();
}
[RollbackAttribute]
public static void Test()
{
Test1();
}
public static void Test1()
{
Test2();
}
public static void Test2()
{
Test3();
}
public static void Test3()
{
Test4();
}
public static void Test4()
{
var framecount = new StackTrace().FrameCount;
System.Reflection.MethodBase method = new StackTrace().GetFrame(framecount-2).GetMethod();
RollbackAttribute rollback = (RollbackAttribute)method.GetCustomAttributes(typeof(RollbackAttribute), true)[0];
}
}
I would like to have a solution to get the attribute value from the Test4 method. But without using StackTrace which is used now. Thank you for any help.
Aucun commentaire:
Enregistrer un commentaire