How do I execute a method at the end of each method in my class C#

Asked

Viewed 661 times

5

He had a father class and another daughter and would like to perform a certain method, as an event, always at the end of each call of the method of the daughter classes. How can I do?

  • 1

    I don’t quite understand what you want to make friend. At the end of each method, want to call another method?

  • 1

    Simply manually add the method there at the end, it will become simpler. If you want to work with events it will be much more complex than simply adding the call to the method.

4 answers

8


That’s called Aspect Oriented Programming (aspect-oriented programming), an orthogonal concept to OOP.

At AOP, methods are decorated with aspects. Generally, there are 3 types of aspects: aspects that are performed before the method, during the method, or afterward of the method.

Unfortunately, C# does not support this paradigm natively.

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

Option 1 - Postsharp

Postsharp and' a tool that allows to decorate methods with attributes that represent aspects of that methods. During the compilation, Postsharp injecting the appearance on the body of the method itself.

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

Option 2 - Interceptors / Castle Dynamic Proxy

Castle Dynamicproxy allows you to dynamically create (in Runtime) 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, what do you want to call a method (for example, CleanUp) after all the calls to the object, the Interceptor would be 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 method CleanUp will be called after all calls to any method at the time of MinhaClass (provided that the instance is decorated with the proxy).

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

About the Dynamicproxy:

This project is very popular. And' 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 mocks.

  3. Ioc containers (Inversion of control / injeccao of dependencies) as Castle Windsor and Ninject.

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

With Dynamicproxy, we can 1) completely separate logging from business logic and 2) define logging on one site, and then apply the Interceptor to several other classes (DRY).

More:

  1. Introducation to AOP with Castle
  2. Dynamicproxy

1

Using a generic method in the parent class:

public void Metodo<T>(T t) where t: IInterfaceClasseFilha
{
    MetodoAntes();
    Metodo(t);
    MetodoDepois();
}

0

I don’t quite understand your doubt, but class with events is like this as an example below:

Event classes:

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();

Exit:

inserir a descrição da imagem aqui

  • 1

    Why implement IDisposable and call the SuppressFinalize if the class has no finalizer?

  • @dcastro, this is an example, and it is correct what I did, logical that who will use should have common sense and observe this.

  • 2

    In this particular case, I thought it was very important to remove this code from the answer. A reader who is not familiar with GC.SupressFinalize may find that it is' good practice to call it whenever it implements IDisposable, when actually less than 1% of implementations need to call the SupressFinalize, and only' in circumstances muuuuuito specific.

0

Use the construction Try/Finaly. The code in the Finaly construction will run always, even if an exception occurs in your class, so you should provide the treatment that should be given properly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.