How do I run a method at the end of each method of my C Class#

Has a parent and a child class and would like to execute a certain method, as an event, always at the end of each child class method call. How can I do it?

Author: Maniero, 2014-06-23

4 answers

This is called Aspect Oriented Programming (Aspect-Oriented Programming ), a concept orthogonal to OOP.

In AOP, methods are decorated with aspects. Generally, there are 3 types of aspects: aspects that are executed before the method, during the method, or after of the method.

Unfortunately, C# does not support this paradigm natively.

However there are 2 ways to use AOP in C#.

Opcao 1 - PostSharp

PostSharp is a tool that allows you to decorate methods with attributes that represent aspects of that method. During compilation, PostSharp injects the aspect into the body of its method.

But PostSharp is a paid tool (with 45 days of trial). If this is not an option, I recommend option 2:

Opcao 2-Interceptors / Castle Dynamic Proxy

Castle DynamicProxy allows you to dynamically (at runtime) create a type that acts as a proxy of another type. The proxy intercepts all calls made on target, and allows you to add logic involving the call.

In your case, How do you want to call a method (e.g. CleanUp) after all calls to the object, the interceptor would look something like this:

public class Interceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        //invocar metodo no target
        invocation.Proceed();

        //invocar aspecto
        MinhaClass obj = invocation.InvocationTarget as MinhaClass;
        if(obj != null)
            obj.CleanUp();
    }
}

The CleanUp method will be called after all calls to any method of the MinhaClass instance (as long as the instance is decorated with the proxy).

Castle DynamicProxy works best when used in conjunction with the Castle Windsor as a tool for dependency injection. Thus, all instances of the class will be automatically decorated with the proxy.

About DynamicProxy:

This project is very popular. E ' used as a basis in:

  1. NHibernate

    For example, NHibernate, an object / relational mapper uses DynamicProxy to provide lazy loading of data without the domain model classes being aware of this functionality.

  2. Various mocking frameworks (such as Moq and RhinoMocks) to dynamically generate the mocks.

  3. IoC containers (Inversion of control / dependency injection) such as Castle Windsor and Ninject.

In my company we occasionally use to add "logging" aspects to some classes, so that all calls to their methods are logged in EventViewer in Log mode. debug.

With DynamicProxy, we can 1) completely separate the logging from the business logic and 2) define the logging in one OS site, and then apply the interceptor to several other classes (DRY).

More:

  1. introducing AOP with Castle
  2. DynamicProxy
 8
Author: dcastro, 2020-06-11 14:45:34

Using a generic method in the parent class:

public void Metodo<T>(T t) where t: IInterfaceClasseFilha
{
    MetodoAntes();
    Metodo(t);
    MetodoDepois();
}
 1
Author: Leonel Sanches da Silva, 2014-06-23 15:44:52

I didn't quite understand your doubt, but, class with events is like this as example below:

classes with event:

public class Pai : IDisposable
{
    public delegate void Acao(int numbers);
    public event Acao Actions;
    public void Execute()
    {
        Actions(1000);
    }

    public void Dispose()
    {
        GC.SuppressFinalize(this);
    }
}

public class Filho : Pai
{

}

using:

static void filho_Actions(int numbers)
{
    System.Console.WriteLine(numbers);
}

Filho filho = new Filho();
filho.Actions += filho_Actions;
filho.Execute();

output:

insert the description of the image here

 0
Author: , 2014-06-23 16:00:24

Use the construct try / finaly . The code in the finaly build will always run, even if an exception occurs in your class, so you should foresee the treatment that must be given properly.

 0
Author: lsalamon, 2014-06-24 11:07:56