Execute builder of an Attribute

3

How do I call the constructor of an attribute before the constructor of the decorated class?

For example, I have my attribute:

using System;    
namespace T.WinForm
{
    public class TesteAttribute : Attribute
    {
        public TesteAttribute()
        {
               Console.WriteLine("Executei o construtor do atributo..."); 
        }
    }
}

And I have the class decorated by the previous attribute:

using System;
namespace SimT.WinForm
{
    public partial class FrmMenuPrincipal : SimTForm
    {
        [TesteAttribute]
        public FrmMenuPrincipal()
        {
            InitializeComponent();
            Console.WriteLine("Executei o construtor da classe...");
        }
    }
}

I would like that when executing this code, the writing sequence of the console would look like this:

  • I ran the attribute constructor ...
  • I ran the class constructor ...
  • The intent is to do something like% co.de% of ASP.Net MVC.

    I'm trying to do this using a WinForms application with .Net 4.5

        
    asked by anonymous 11.05.2016 / 02:27

    1 answer

    3

    Understand how this decorator works .

    To call all attributes of all methods you must have a code somewhere that the attributes are "called". This is done through reflection that will read the existing metadata . The execution can be done in several ways.

    A simple way to do this is to have a method that is invoked in the constructor of SimTForm or a base class above it, ie it has to be manual, but does not have to be manual everywhere, it can encapsulate the running into a base class that will always be used and abstracting various things, among them the call of attributes. Thus simple inheritance "automates" the execution of attribute constructors.

    It is not a good idea to call the constructor directly because doing so will completely lose the attribute's usefulness. If you explicitly call the constructor does not need anything else to decorate the method.

    Then the base class should "list" all methods that are of interest to you (you can filter in a number of ways, read the documentation and use the creativity) and invoke its attributes.

    Code that takes the methods of the current class:

    this.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance)
    

    Documentation for GetMethods() .

    To call the attributes:

    method.GetCustomAttributes(true);
    

    Documentation for GetCustomAttributes() .

    See running on dotNetFiddle and CodingGround .

    Obviously needs to adapt to your need. Remembering that there are other ways of obtaining the same result and perhaps for the sunset of the AP, some of them are more appropriate.

        
    11.05.2016 / 15:42