Search code examples
c#aopcustom-attributespostsharp

How Can an Attribute Class Reference the Instance that Uses It?


Let's say I have an attribute class:

public class MyCustomAttribute : Attribute
{
    // do stuff
}

And I use this attribute on class properties:

public class MyModel : BaseModel
{
    [MyCustom]
    public string Name { get; set; }
}

Is there a way, within the code of MyCustomAttribute, to reference the instance of MyModel on which it's being used?

Ultimately I'm just experimenting with AOP (using PostSharp) to create attributes to track when a model is dirty. So if BaseModel has an IsDirty property then I'd like to be able to do something like this with PostSharp:

public class TrackDirtyPropertyAttribute : OnMethodBoundaryAspect
{
    public override void OnSuccess(MethodExecutionArgs args)
    {
        someReferenceToTheObject.IsDirty = true;
    }
}

I've tried passing a reference into the attribute's constructor:

public class TrackDirtyPropertyAttribute : OnMethodBoundaryAspect
{
    private BaseModel _currentObject { get; set; }

    public TrackDirtyPropertyAttribute(BaseModel currentObject)
    {
        _currentObject = currentObject;
    }

    public override void OnSuccess(MethodExecutionArgs args)
    {
        _currentObject.IsDirty = true;
    }
}

However, when I use it:

[TrackDirtyProperty(this)]
public string Name { get; set; }

It tells me that this is not available in that context.


Solution

  • You should do it like this:

    public class TrackDirtyPropertyAttribute : OnMethodBoundaryAspect 
    { 
        public override void OnSuccess(MethodExecutionArgs args) 
        { 
            ((BaseModel) args.Instance).IsDirty = true; 
        } 
    }