C#C
C#17mo ago
Cracker

How do I manage singleton Regex initialization in Scoped service ?

both IMaskingOperator and IMaskingPolicy is scoped service. I have regex pattern used with value of scoped service. In this case for performance, how can I ensure the regex is initialized only once ?

    public class DefaultMaskingOperator : IMaskingOperator
    {
        private Regex regex;
        public DefaultMaskingOperator(IMaskingPolicy policy)
        {
            string pattern = $"...{policy.MaskKeyList}...";
            regex = new Regex(pattern,RegexOptions.Compiled);
        }

        public string MaskWithRegex(string input)
        {
            string output = string.Empty;
            var matches = regex.Matches(input);
            //...
            return output;
        }
    }
Was this page helpful?