Search code examples
postsharp

Postsharp introduce Attributes with Property Arguments


I am trying to achieve attribute introduction like here but my attributes have property arguments like: [Foo(Bar = "Baz")]

How do I correctly pass the arguments? I'm not copying the attributes from something else, so I don't think I can use CustomAttributeData?


Solution

  • You can set properties of your custom attributes by using ObjectConstruction.NamedArguments dictionary.

    For example:

    public IEnumerable<AspectInstance> ProvideAspects(object targetElement)
    {
        Type targetType = (Type) targetElement;
    
        var objectConstruction =
            new ObjectConstruction(typeof (MyCustomAttribute).GetConstructor(Type.EmptyTypes));
        objectConstruction.NamedArguments["Bar"] = "Baz";
    
        var introduceAttributeAspect = new CustomAttributeIntroductionAspect(objectConstruction);
    
        yield return new AspectInstance(targetType, introduceAttributeAspect);
    }