'ASP.NET Core : how to restrict applying custom attribute on condition during compile time?
Here is the sample code:
public sealed class CustomAttribute1 : Attribute
{}
public sealed class CustomAttribute2 : Attribute
{}
[CustomAttribute1]
[CustomAttribute2]
public async Task<IActionResult> UpdateAsync(Userodel userModel) //assume it as an action inside a mvc controller
{ }
As per the business need, UpdateAsync() can be either decorated with [CustomAttribute1] or [CustomAttribute2], or without none of them, but NOT with both of them for the SAME action method.
How to restrict the developer (at compile time) from decorating an action method with both [CustomAttribute1] and [CustomAttribute2] ?
Solution 1:[1]
In project properties, in Compilation, there are a TextBox "Conditionally compilation symbols". Define, for example MODE1. Then, in your code:
#if MODE1
[CustomAttribute1]
#elif MODE2
[CustomAttribute1]
#endif
public async Task<IActionResult> UpdateAsync(...)
Now, you can need create some configurations, like the DEBUG and RELEASE created by default. Create, for example, DEBUG1 and DEBUG2 and set MODE1 to DEBUG1 and MODE2 to DEBUG2.
If you debug with DEBUG1 configuration, you'll use CustomAttribute1. With DEBUG2, CustomAttribute2. And with DEBUG, none of them.
UPDATE
Sorry, I missunderstood your question. May be an option move the solution to the attribute implementation?
[AttributeUsage(AllowMultiple = false)]
public sealed class CustomAttribute : Attribute
{
private bool _useMode1;
public CustomAttribute(bool useMode1)
{
_useMode1 = useMode1;
}
// Do things in a way or other depending of _useMode1
}
With previous approach, you have only one attribute and use the parameter to select between your current 1 and 2 attributes. Also, you can't add more than once (because AttributeUsage -> AllowMultiple):
[CustomAttribute(true)]
public async Task<IActionResult> UpdateAsync(...)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
