重构C#服务注册方法:将单前缀参数改为字符串数组
Refactored C# Method for Multiple Prefix Filtering
Let's adjust the method to support multiple prefixes and update the filtering logic accordingly. Here's the cleaned-up, refactored code:
private void RegisterServices(IServiceCollection serviceCollection, Container container, string[] solutionPrefixes) { // Optional guard clause to avoid unexpected behavior with empty/null input if (solutionPrefixes == null || solutionPrefixes.Length == 0) { throw new ArgumentException("You must provide at least one solution prefix.", nameof(solutionPrefixes)); // Alternatively, return early or include all assemblies if that's your intended behavior } var types = AppDomain.CurrentDomain.GetAssemblies() .Where(a => solutionPrefixes.Any(prefix => a.FullName?.StartsWith(prefix) ?? false)) .SelectMany(x => x.GetTypes()) .Where(x => !x.IsAbstract && !x.IsGenericTypeDefinition); // Rest of your registration logic... }
Key Changes Breakdown:
- Parameter Update: Swapped the single
string solutionPrefixparameter for astring[] solutionPrefixesto accept multiple prefix values. - Null-Safe Filtering: Used
a.FullName?.StartsWith(prefix) ?? falseto handle edge cases where an assembly'sFullNamemight be null (preventsNullReferenceExceptionand excludes those assemblies). - Multiple Prefix Check: Replaced the single prefix match with
solutionPrefixes.Any(...)to include assemblies that start with any of the provided prefixes. - Guard Clause: Added a check to catch null/empty prefix arrays early—this prevents silent failures where no assemblies would be filtered (since
Any()on an empty array returns false).
Optional Adjustments:
- Case-Insensitive Matching: If you need to ignore case when checking prefixes, modify the
StartsWithcall:a.FullName?.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) ?? false - Allow Empty Prefixes: If an empty array should mean "include all assemblies", adjust the Where clause:
.Where(a => solutionPrefixes.Length == 0 || solutionPrefixes.Any(prefix => a.FullName?.StartsWith(prefix) ?? false)) - Skip Empty Prefix Entries: To ignore null/empty strings in the prefix array:
.Where(a => solutionPrefixes.Where(p => !string.IsNullOrEmpty(p)).Any(prefix => a.FullName?.StartsWith(prefix) ?? false))
内容的提问来源于stack exchange,提问作者Milad
相关产品推荐
相关产品推荐

