2011-10-05 39 views
1

我使用下面的PostSharp方面来验证类的属性。每个实例只有一次PostSharp方面调用

[ProtoContract] 
    public sealed class Web2Image : WebEntity 
    { 
     [ProtoMember(1009), Validator.Collection(Data = new[] { "jpg", "bmp", "png", "tiff" })] 
     public override string OutputFormat { get; set; } 
} 

属性OUTPUTFORMAT验证上的第一属性的访问,但验证被执行,并且当属性中的代码访问的第二和第三时间。 我想限制只执行一次每个类实例的Aspect执行我的属性。怎么做?

public class Validator 
    { 

     [Serializable] 
     [Collection(AttributeExclude = true)] 
     [MulticastAttributeUsage(MulticastTargets.Property)] 
     public class Collection : LocationInterceptionAspect 
     { 
      public string[] Data; 

      public override void OnGetValue(LocationInterceptionArgs args) 
      { 

       SiAuto.Main.LogObject("FieldAccessEventArgs " + Reflection.AssemblyHelper.EntryAssembly, args); 
       /* SiAuto.Main.LogObject("FieldAccessEventArgs " + Reflection.AssemblyHelper.EntryAssembly, args.Binding.ToString());*/ 

       args.ProceedGetValue(); 
       if (args.Value == null) 
       { 
        args.Value = Data[0]; 
        args.ProceedSetValue(); 
       } 

       foreach (var s in Data) 
       { 
        if (args.Value.ToString().ToLower() == s.ToLower()) 
         return; 

       } 

       throw new EngineException(string.Format("Value \"{0}\" is not correct. {1} parameter can accept only these values {2}", args.Value, args.LocationName, string.Join(",", Data))); 

      } 

     } 
} 

回答

0

您将需要实现IInstanceScopedAspect。请参阅http://www.sharpcrafters.com/blog/post/Day-9-Aspect-Lifetime-Scope-Part-1.aspxhttp://www.sharpcrafters.com/blog/post/Day-10-Aspect-Lifetime-Scope-Part-2.aspx了解有关方面的生命周期和范围的更多信息,包括如何实现IInstanceScopedAspect。

这将为您带来每个实例的方面(因为现在每个类型都有一次)。至于检查,你可以设置一个开关(如果是true,否则退出,检查)或检查它是否为空(或其他初始值)。

相关问题