0

I am working with asp.net mvc4 and have a form where I accept data from a user. Input fields like name, address etc.

I want to be able to validate such with the normal mvc validation attributes but as the site varies based upon the certain parameters, I hold the regex for each attribute in a configuration file that gets loaded at runtime based upon the user (their culture etc). I am using spring.net for dependency injection.

Is it possible to perform dependency injection into custom attributes at runtime and if so, how?

amateur
  • 43,371
  • 65
  • 192
  • 320

2 Answers2

2

The values in the attribute methods are limited to constant values. e.g. strings, numbers and typeof.

What you can do, is derive a new attribute from the RegularExpressionAttribute that will take in the constructor a key to find the regex.

[MyRegularExpression("Field1")]
public string Field1 { get; set; }

the attribute:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class MyRegularExpressionAttribute : RegularExpressionAttribute
{
    public MyRegularExpressionAttribute(string key)
        : base(FindRegex(key))
    { }

    private static string FindRegex(string key)
    {
        ...
    }
}
Michael
  • 83
  • 4
0

You can create custom attributes by extending from ValidationAttribute, and pass in your data-store dependencies to the constructor. Now apply this attribute to your model's properties and register the same with your DI container.

And yes, the dependencies can be injected at run-time as well. In Castle Windsor DI, you can specify LifeStyles for the dependencies such as 'Transient' - I'm pretty sure there should be something like that for spring.net

aquaraga
  • 4,138
  • 23
  • 29