Stashbox by Peter Csajtai

<PackageReference Include="Stashbox" Version="2.9.0-preview-524" />

 ServiceRepositoryExtensions

using Stashbox.Entity; using Stashbox.Registration.SelectionRules; using Stashbox.Resolution; using Stashbox.Utils; using System; using System.Collections.Generic; using System.Linq; namespace Stashbox.Registration.Extensions { internal static class ServiceRepositoryExtensions { public static bool ContainsRegistration(this ImmutableTree<Type, ImmutableArray<object, IServiceRegistration>> repository, Type type, object name) { ImmutableArray<object, IServiceRegistration> orDefault = repository.GetOrDefault(type); if (name != null && orDefault != null) return orDefault.GetOrDefault(name) != null; if (orDefault != null || !type.IsClosedGenericType()) return orDefault != null; orDefault = repository.GetOrDefault(type.GetGenericTypeDefinition()); if (orDefault == null) return false; return orDefault.Any((IServiceRegistration reg) => reg.ValidateGenericConstraints(type)); } public static IServiceRegistration SelectOrDefault(this IEnumerable<IServiceRegistration> registrations, TypeInformation typeInformation, ResolutionContext resolutionContext, IRegistrationSelectionRule[] registrationSelectionRules) { int index = 0; List<IServiceRegistration> list = new List<IServiceRegistration>(); int num = 0; foreach (IServiceRegistration registration in registrations) { if (registrationSelectionRules.IsSelectionPassed(typeInformation, registration, resolutionContext, out int weight)) { list.Add(registration); if (weight >= num) { num = weight; index = list.Count - 1; } } } if (list.Count != 0) return list[index]; return null; } public static IEnumerable<IServiceRegistration> FilterOrDefault(this IEnumerable<IServiceRegistration> registrations, TypeInformation typeInformation, ResolutionContext resolutionContext, IRegistrationSelectionRule[] registrationSelectionRules) { List<IServiceRegistration> list = new List<IServiceRegistration>(); List<IServiceRegistration> list2 = new List<IServiceRegistration>(); foreach (IServiceRegistration registration in registrations) { if (registrationSelectionRules.IsSelectionPassed(typeInformation, registration, resolutionContext, out int weight)) { if (weight > 0) list2.Add(registration); list.Add(registration); } } if (list.Count != 0) { if (list2.Count <= 0) return list; return list2; } return null; } private static bool IsSelectionPassed(this IRegistrationSelectionRule[] registrationSelectionRules, TypeInformation typeInformation, IServiceRegistration serviceRegistration, ResolutionContext resolutionContext, out int weight) { weight = 0; int num = registrationSelectionRules.Length; for (int i = 0; i < num; i++) { if (!registrationSelectionRules[i].IsValidForCurrentRequest(typeInformation, serviceRegistration, resolutionContext)) return false; if (registrationSelectionRules[i].ShouldIncrementWeight(typeInformation, serviceRegistration, resolutionContext)) weight++; } return true; } } }