简体   繁体   中英

executing a method after several methods run

I have a class that looks like this:

public class SomeClass
{
   public void SomeMethod1() { ... }
   public void SomeMethod2() { ... }
   public void SomeMethod3() { ... }

   private void SomeSpecialMethod(SomeParameter) { ... }
}

For the moment, I have each of the first 3 methods call SomeSpecialMethod() just before these method return. I'm going to add about 15 more methods that in the end all need to execute SomeSpecialMethod() and I'm wondering if there's a way to say "when any of the methods in this class run, execute SomeSpecialMethod() " without having to explicitly repeat the call at the end of every method and of course prevent SomeSpecialMethod() from calling itself infinitely.

Thanks for your suggestions.

You're looking for AOP - aspect oriented programming.

C# doesn't follow this paradigm, but you can mimic it. PostSharp is one option, but I'd go with Castle interceptors / DynamicProxy instead: http://docs.castleproject.org/Windsor.Interceptors.ashx

You will need to create an interceptor that wraps around your object and intercepts calls to it. At runtime, Castle will make this interceptor either extend your concrete class or implement a common interface - this means you'll be able to inject the interceptor into any piece of code that targets SomeClass . Your code would look something like this:

public class Interceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
       invocation.Proceed();
       //add your "post execution" calls on the invocation's target
    }
}

Edit

Introduction to AOP with Castle: http://docs.castleproject.org/Windsor.Introduction-to-AOP-With-Castle.ashx

Interceptors, and AOP in general, are usually used for things such as logging the result of every method call of an object, or logging every exception thrown by any method.

If the logic inside SomeSpecialMethod is abstract and not really related to SomeClass (like logging, for example), it might make sense to move the logic to the interceptor itself - but that's up to you.

I once faced such a problem and solved it like this: declared an auxuliary nested class (say, X ) without any fields/methods, only with a constructor that takes an object of SomeClass and calls its SomeSpecialMethod() . Then made all SomeClass 's methods return that X :

public X SomeMethod1() { 
     ... 
     return new X(this);
}

Of course, there is an overhead, and you can do this with non- void methods (well, you can, but it'll get ugly).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM