Search code examples
c#.netinotifypropertychangedpostsharp

PostSharp MulticastAttributeUsage not working


I have trouble with PostSharp and Entity Framework, because PostSharp generates "backingField" properties for private fields and it EDM model creating is failed. I have tried to use a MulticastAttributeUsageAttribute.AttributeTargets to restrict it to properties as described here. But this code:

[NotifyPropertyChanged(), MulticastAttributeUsage(MulticastTargets.Property)]
public abstract class MetrologijaEntityBase 
{
    public Guid Id { get; set; }
    public string ExternalKey { get; set; }
}

and this code

[NotifyPropertyChanged()]
[MulticastAttributeUsage(MulticastTargets.Property)]
public abstract class MetrologijaEntityBase 
{
    public Guid Id { get; set; }
    public string ExternalKey { get; set; }
}

gives the same result as code without MulticastAttributeUsage attribute - "backingField" properties (with all getters and setters) for private fields are still generated (as it visible in IL Disassambler for my class). MetrologijaEntityBase is the base class for EF business model entity hierarchy. What I am doing wrong in this case?


Solution

  • [MulticastAttributeUsage] changes the default behavior of the MulticastAttribute it is applied to and does not have any effect when applied to classes that do not inherit from MulticastAttribute. It can be used to change the default behavior of your own aspect. It does not change the behavior of an aspect being applied to the same declaration (you can usually do that by changing properties on the aspect itself).

    [NotifyPropertyChanged] is a type-level aspect and it is applied to whole types. It's not generally possible to control what it does to individual properties unless the aspect itself supports that (which NPC aspect currently does not).

    As a solution, I'd suggest programmatically ignoring added properties based on their name when creating the EF model as mentioned here.