Skip to content

Commit

Permalink
Improve MauiFactory performance by avoiding reflection to get base cl…
Browse files Browse the repository at this point in the history
…asses
  • Loading branch information
albyrock87 committed Sep 22, 2024
1 parent 0de3f8a commit bb8e201
Showing 1 changed file with 10 additions and 8 deletions.
18 changes: 10 additions & 8 deletions src/Core/src/Hosting/Internal/MauiFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;

namespace Microsoft.Maui.Hosting.Internal
Expand All @@ -11,6 +13,7 @@ class MauiFactory : IMauiFactory
{
static readonly Type EnumerableType = typeof(IEnumerable<>);
static readonly Type ListType = typeof(List<>);
static readonly ConcurrentDictionary<Type, IReadOnlyList<Type>> ServiceBaseTypes = new();

readonly IMauiServiceCollection _collection;

Expand Down Expand Up @@ -98,23 +101,22 @@ protected bool TryGetServiceDescriptors(ref Type serviceType, out ServiceDescrip
return false;
}

static List<Type> GetServiceBaseTypes(Type serviceType)
static IReadOnlyList<Type> GetServiceBaseTypes(Type serviceType) =>
ServiceBaseTypes.GetOrAdd(serviceType, ServiceBaseTypesFactory);

static IReadOnlyList<Type> ServiceBaseTypesFactory(Type type)
{
var types = new List<Type> { serviceType };
var types = new List<Type> { type };

Type? baseType = serviceType.BaseType;
Type? baseType = type.BaseType;

while (baseType != null)
{
types.Add(baseType);
baseType = baseType.BaseType;
}

foreach (var interfac in serviceType.GetInterfaces())
{
if (typeof(IView).IsAssignableFrom(interfac))
types.Add(interfac);
}
types.AddRange(type.GetInterfaces().Where(typeof(IView).IsAssignableFrom));

return types;
}
Expand Down

0 comments on commit bb8e201

Please sign in to comment.