I use PostSharp aspect below to validate Property of the class.
[ProtoContract]
public sealed class Web2Image : WebEntity
{
[ProtoMember(1009), Validator.Collection(Data = new[] { "jpg", "bmp", "png", "tiff" })]
public override string OutputFormat { get; set; }
}
The property OutputFormat is validated on first property access but Validation is executed and second and third time when property accessed in the code. I would like to limit Aspect execution only once per class instance for my property. How to do that?
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)
开发者_如何学Python {
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)));
}
}
}
You will need to implement IInstanceScopedAspect. See http://www.sharpcrafters.com/blog/post/Day-9-Aspect-Lifetime-Scope-Part-1.aspx and http://www.sharpcrafters.com/blog/post/Day-10-Aspect-Lifetime-Scope-Part-2.aspx for more about the lifetime and scope of aspects including how to implement IInstanceScopedAspect.
That will get you the per instance aspect (because right now it's once per type).
As far as the checking, you can set a switch (if true, exit otherwise, do check) or check if it's null (or some other initial value).
精彩评论