Calling an alternate method in a class using postsharp

I want to be able to call the differnt method for my intercepted class using PostSharp .

Let's say I have the following method in my aspect of PostSharp :

  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 } } 

CallDifferentMethod() is another method inside the class that has been intercepted. I can do reflection magic to get the name of what I want to call, but I cannot figure out how to call this method for this instance of the class. I do not want to unwind a new instance of the class

Any suggestions?

+4
source share
1 answer

Do you throw args.Instace to your type? Based on what you wrote, I would suggest 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 this interface.

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

or directly on the interface

 [MyAspect] public interface IHasFeature 

Update: Sorry, Gael is right. Sorry about that. Use the CompileTimeValidate method in order to LIMIT 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

+3
source

All Articles