0

I have one class and I want to have custom attribute, so on class level I can do it without any problem.

Example:

[@Component]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class AuthUserController : ApiController
{
       // functions and their logic ...
}

Here @Compunent is my custom attribute and EnableCors is third party attribute. I can do it without any problem, even i can read my attribute also. Below code.

type = Namespace.MyClassName.GetType();
System.Attribute[] attrs = System.Attribute.GetCustomAttributes(type);

So my question is how to apply same custom attribute on Constructor level something like this.

[@Component]
public AuthUserController(AuthenticationService objAuthenticationService)
{
     // code 
}

Above code is fine it is not showing any error but how to read constructor level attribute is my question. By using above first technique its not working.

Please help.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
Md IstiyaQ
  • 21
  • 3
  • 1
    Possible duplicate of [Read the value of an attribute of a method](https://stackoverflow.com/questions/2493143/read-the-value-of-an-attribute-of-a-method) – Sinatr Feb 16 '18 at 12:24
  • Constructor is just another method of the type. So you have to read attributes of method, not ones of the type as you doing now. – Sinatr Feb 16 '18 at 12:26

1 Answers1

0

You need to find a constructor and then get attributes from them. You can do this with linq - next code fetch all constructors and attributes:

var type = typeof(MyClassName);
var ctors = type
    .GetConstructors()
    .Select(c => new { ctor = c, attribytes = c.GetCustomAttributes(inherit: false)})

    // Optional - you can filter out constructors without attributes
    .Where(x => x.attribytes.Any())

    .ToArray();

foreach (var ctor in ctors)
{
    Console.WriteLine($"{ctor.ctor} has attributes:\n{string.Join("\n", ctor.attribytes)}");
}

Note, that GetConstructors will return only public constructors. If you need all you can use an overload of this method and pass a BindingFlags argument

Aleks Andreev
  • 7,016
  • 8
  • 29
  • 37