Let's say I have an interface IAppModule
, implemented by a few classes. Is it at all possible to write a custom attribute that can only be applied to types that expose IAppModule
? If so, how?
In C#, attributes are classes that inherit from the Attribute base class. Any class that inherits from Attribute can be used as a sort of "tag" on other pieces of code. For instance, there is an attribute called ObsoleteAttribute . This is used to signal that code is obsolete and shouldn't be used anymore.
C# Language Attributes Reading an attribute from interface There is no simple way to obtain attributes from an interface, since classes does not inherit attributes from an interface. Whenever implementing an interface or overriding members in a derived class, you need to re-declare the attributes.
With attribute-based routing, we can use C# attributes on our controller classes and on the methods internally in these classes. These attributes have metadata that tell ASP.NET Core when to call a specific controller. It is an alternative to convention-based routing.
Attributes are used for adding metadata, such as compiler instruction and other information such as comments, description, methods and classes to a program. The . Net Framework provides two types of attributes: the pre-defined attributes and custom built attributes.
No, unfortunately it's not possible.
You can, however, when using reflection to process your attributes, check if the decorated type is a class that implements the IAppModule interface.
typeof(someType).GetInterfaces().Contains(typeof(IAppModule))
It doesn't stop users of your attribute from using it incorrectly (in any other class), but if you decide to go with this approach, I'd recommend providing very clear documentation describing how the attribute should be used and adding the layer of validation I mentioned above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With