Reputation: 665
I am currently trying to convert my company's development framework to .NET 5 from .NET framework 4.7.
In old code there are a series of custom validation attributes that inherit from System.ComponentModel.DataAnnotations.RegularExpressionAttribute.
These all have the following behaviour
How do I access the configuration from inside a Data Annotation Validation attribute in .NET 5.
I know I could create a static Configure method on all validation attributes and manually inject the IConfiguration on app Startup but this seems clunky and inelegant, so I'm hoping there's a better way.
I'd rather not have to pass the value from the config file in as a parameter every time I use the attribute as this somewhat defeats the point of our custom regex validation attributes and also adds the possibility of someone making a mistake and passing an incorrect value into the attribute.
In the .NET framework version access to the config file was done with configuration manager. In .NET 5 this is not really an option (as I'm trying to move away from *.config files to .NET core's more flexible system)
I've done searches for how to inject into ASP.Net core attributes but all results I found seem to relate to Actionfilter and ServiceFilter, which doesn't seem to have much relevance for Data Annotation Attributes
Upvotes: 2
Views: 1493
Reputation: 686
You can try a variation of this:
var config = (IConfiguration)validationContext.GetService(typeof(IConfiguration));
Upvotes: 3