I have an abstract class for entities which are responsible for generating and returning an unique key for every Entity instance. The key generation is a bit costly and is based on the property values of the concrete entity. I already mark the properties participating in key generation with KeyMemberAttribute
so all I'd need is to make the EntityBase.Key
= null every time a property decorated with KeyMemberAttribute
changes.
So, I got the base class like so:
public abstract class EntityBase : IEntity
{
private string _key;
public string Key {
get {
return _key ?? (_key = GetKey);
}
set {
_key = value;
}
}
private string GetKey { get { /* code that generates the entity key based on values in members with KeyMemberAttribute */ } };
}
Then I got the concrete entities implemented as follows
public class Entity : EntityBase
{
[KeyMember]
public string MyProperty { get; set; }
[KeyMember]
public string AnotherProperty { get; set; }
}
I need to make the KeyMemberAttribute
to set the EntityBase.Key
to null
every time a property value changes.
Have a look at an Aspect Oriented Programming (AOP) Framework such as PostSharp. PostSharp allows you to create attributes which you can use to decorate classes, methods...etc.
Such an attribute can be programmed to inject code before your setter executes and after its finished.
for example with postSharp you can define your attribute like:
[Serializable]
public class KeyMemberAttribute : LocationInterceptionAspect
{
public override void OnSetValue(LocationInterceptionArgs args)
{
args.ProceedSetValue();
((EntityBase)args.Instance).Key=null;
}
}
So on every call to any property decorated with KeyMemberAttribute
your key will be set to null.