© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
15 replies
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;
        }
    }
    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;
        }
    }
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

✅ Scoped, Singleton and HostedService
C#CC# / help
3y ago
Managing Scoped Service Lifecycles with a Singleton Factory in .NET: Best Practices?
C#CC# / help
17mo ago
get scoped service
C#CC# / help
3y ago
✅ Cannot resolve scoped service...
C#CC# / help
4y ago