Skip to content

Commit

Permalink
feat: Improve DI extensions
Browse files Browse the repository at this point in the history
  • Loading branch information
曹尤先 authored and blazor-component committed Dec 9, 2021
1 parent 4e44ac7 commit 36c2093
Showing 1 changed file with 12 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
namespace Microsoft.Extensions.DependencyInjection;

public static class ServiceCollectionExtensions
{
/// <summary>
Expand All @@ -19,7 +20,7 @@ public static IServiceCollection AddServices(this IServiceCollection services, s
/// <returns></returns>
public static IServiceCollection AddServices(this IServiceCollection services, string suffix, bool autoFire, params Assembly[] assemblies)
=> (from type in assemblies.SelectMany(assembly => assembly.GetTypes())
where type.Name.EndsWith(suffix)
where !type.IsAbstract && type.Name.EndsWith(suffix)
select type).AddScoped(services, autoFire);

/// <summary>
Expand All @@ -45,7 +46,7 @@ public static IServiceCollection AddServices<TService>(this IServiceCollection s
/// <returns></returns>
public static IServiceCollection AddServices<TService>(this IServiceCollection services, bool autoFire, params Assembly[] assemblies)
=> (from type in assemblies.SelectMany(assembly => assembly.GetTypes())
where type.BaseType == typeof(TService)
where !type.IsAbstract && BaseOf<TService>(type)
select type).AddScoped(services, autoFire);

private static IServiceCollection AddScoped(this IEnumerable<Type> serviceTypes, IServiceCollection services, bool autoFire)
Expand All @@ -62,6 +63,14 @@ private static IServiceCollection AddScoped(this IEnumerable<Type> serviceTypes,
services.BuildServiceProvider().GetService(serviceType);
}
}

return services;
}
}

private static bool BaseOf<T>(Type type)
{
if (type.BaseType == typeof(T)) return true;

return type.BaseType != null && BaseOf<T>(type.BaseType);
}
}

0 comments on commit 36c2093

Please sign in to comment.