Search code examples
c#aoppostsharp

Call alternative method in class using postsharp


I want to be able to call a differnt method on my intercepted class by using PostSharp.

Say I have the following method in my PostSharp aspect:

    public override void OnInvoke(MethodInterceptionArgs args)
    {
        if (!m_featureToggle.FeatureEnabled)
        {
            base.OnInvoke(args);
        }
        else
        {
            var instance = args.Instance;
            instance.CallDifferentMethod(); //this is made up syntax
        }  
    }

The CallDifferentMethod() is another method within the class that has been intercepted. I can do some reflection magic to get the name of what I want to be called, but I can't work out how to call that method on this instance of the class. I don't want to spin up a new instance of the class

Any suggestions?


Solution

  • Are you casting args.Instace to your type? Based on what you wrote, I'd imagine that your "FeatureEnabled" should be defined through an interface.

    public interface IHasFeature
    {
      bool IsFeatureEnabled { get; set; }
      void SomeOtherMethod();
    }
    

    then use

    ((IHasFeature)args.Instance).SomeOtherMethod(); 
    

    Then apply the aspect to that interface.

    [assembly: MyApp.MyAspect(AttributeTargetTypes = "MyApp.IHasFeature")]
    

    or on the interface directly

    [MyAspect]
    public interface IHasFeature
    

    Update: Oops, Gael is right. Sorry about that. Use the CompileTimeValidate method to LIMIT the aspect at compile time.

    public override bool CompileTimeValidate(System.Reflection.MethodBase method)
            {
                bool isCorrectType = (Check for correct type here)
                return isCorrectType;
            }
    

    For more information, see my post http://www.sharpcrafters.com/blog/post/Day-9-Aspect-Lifetime-Scope-Part-1.aspx