C
C#•4mo 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;
}
}
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;
}
}
11 Replies
Angius
Angius•4mo ago
I'd probably use a regex source generator and some helper static class Other than that, if you want to use DI, create some RegexService or whatever and register it as a singleton Then inject it wherever needed
Cracker
CrackerOP•4mo ago
I tried static properties and getter with lock but its kinda ugly, I will stick with singleton regex service IMaskingPolicy is scoped so regex with MaskKeyList is initialized first and once, but its okay that list wont change often
jcotton42
jcotton42•4mo ago
@Cracker just use the regex source generator
Cracker
CrackerOP•4mo ago
I think its not available in .net 6
jcotton42
jcotton42•4mo ago
Then look to migrate, support runs out in November.
Cracker
CrackerOP•4mo ago
yep thats scheduled, cant do it in a day since huge mono app :/ Still, this feature seems useful. Will use it eventually
Angius
Angius•4mo ago
Just write a Python script to get all *.csproj files and replace net6.0 with net8.0 :when:
Cracker
CrackerOP•4mo ago
I wish 😄
jcotton42
jcotton42•4mo ago
Python? Just run sed recursively.
Angius
Angius•4mo ago
Or that
Want results from more Discord servers?
Add your server