InstanceLevelAspects being applied to static classes

daverant's Avatar


20 Aug, 2017 02:13 PM


To enhance logging in our system (currently using postsharp with an nlog backend), I'm looking to make use of an InstanceLevelAspect to override object.ToString() across an assembly, source code at the end of this question.

However, when applying the attribute at assembly level [assembly: ToStringSerialization], I'm seeing postsharp inject a ToString() instance implementation into static classes e.g.


public static class MyClass
public static class MyClass
    private ToStringSerializationAttribute <>z_aspect49;
    public override string ToString()
        return this.<>z_aspect49.ToString();
I'm looking for some advice on preventing this happening. The working options so far are:
a) Just use static methods, no static classes
b) Apply [ToStringSerialization(AttributeExclude = true)] to static classes

Is there a way to prevent this with multicast targets? I have tried applying [assembly: ToStringSerialization(AttributeTargetTypeAttributes = MulticastAttributes.Instance)] instead, but see no change. I'm using postsharp 4.3.36



using System;
using PostSharp.Aspects;
using PostSharp.Aspects.Advices;
using ServiceStack;

public sealed class ToStringSerializationAttribute : InstanceLevelAspect
    private readonly SerializationFormat _serializationFormat;

    public ToStringSerializationAttribute(SerializationFormat serializationFormat = SerializationFormat.Jsv)
        _serializationFormat = serializationFormat;

    [IntroduceMember(OverrideAction = MemberOverrideAction.OverrideOrFail)]
    public override string ToString()
        switch (_serializationFormat)
            case SerializationFormat.Jsv:
                return Instance.ToSafeJsv();
            case SerializationFormat.Json:
                return Instance.ToSafeJson();
                throw new ArgumentOutOfRangeException();
  1. Support Staff 1 Posted by PostSharp Techn... on 23 Aug, 2017 10:15 AM

    PostSharp Technologies's Avatar


    it's currently not possible with multicasting, you would need to add this logic to aspect's CompileTimeValidateMethod as following:

    public override bool CompileTimeValidate(Type type)
        if ((type.Attributes & (TypeAttributes.Abstract | TypeAttributes.Sealed)) == (TypeAttributes.Abstract | TypeAttributes.Sealed))
            return false;
        return true;

    Best regards,

  2. 2 Posted by daverant on 30 Aug, 2017 11:02 AM

    daverant's Avatar

    That's great, thanks Daniel.

  3. daverant closed this discussion on 30 Aug, 2017 11:02 AM.

Comments are currently closed for this discussion. You can start a new one.

Keyboard shortcuts


? Show this help
ESC Blurs the current field

Comment Form

r Focus the comment reply box
^ + ↩ Submit the comment

You can use Command ⌘ instead of Control ^ on Mac