Serge Intern
Serge Intern

Reputation: 2969

Force property on method parameter before excecution (using PostSharp?)

I have a method like this

public void MyMethod(MyType parameter) { /* ... */ }

I'd like to force a value into one of parameter's public property before the method gets excecuted. It must happen before method excecution because some postSharp OnMethodBoundaryAspect.OnEntry depends on this property's value.

An ideal solution could looks like this:

[SetPropertyBeforeEntry(0 /*  Argument's index*/, nameof(MyType.MyProperty) /* Property to set */, 1234 /* Value */)]
public void MyMethod(MyType parameter) { /* ... */ }

Upvotes: 0

Views: 158

Answers (1)

Daniel Balas
Daniel Balas

Reputation: 1850

You have two options - OnMethodBoundaryAspect and MethodInterceptionAspect, but in both cases you need to use aspect dependencies to make sure you have proper order (PostSharp would produce warnings if the order is not specified).

PostSharp provides various ways to specify dependencies between aspects. You can find more here.

The following demonstrates changing of the parameter's property before (without the specific logic for argument type, property or index.

class Program
{
    static void Main(string[] args)
    {
        new TestClass().Foo(new TestData());
    }
}

public class TestClass
{
    [ObservingAspect]
    [ArgumentChangingAspect]
    public int Foo(TestData data)
    {
        Console.WriteLine("Method observed: {0}", data.Property);

        return data.Property;
    }
}

public class TestData
{
    public int Property { get; set; }
}

[AspectTypeDependency(AspectDependencyAction.Order, AspectDependencyPosition.Before, typeof(ObservingAspect))]
[PSerializable]
public class ArgumentChangingAspect : OnMethodBoundaryAspect
{
    public override void OnEntry(MethodExecutionArgs args)
    {
        ((TestData) args.Arguments[0]).Property = 42;
    }
}

[PSerializable]
public class ObservingAspect : OnMethodBoundaryAspect
{
    public override void OnEntry(MethodExecutionArgs args)
    {
        Console.WriteLine("Aspect observed: {0}", ((TestData)args.Arguments[0]).Property);
    }
}

Upvotes: 1

Related Questions