Skip to content

Commit eb074f8

Browse files
committed
improve voter service resolving
1 parent 18df93e commit eb074f8

2 files changed

Lines changed: 19 additions & 3 deletions

File tree

AuthorizationChecker/src/Extensions/ServiceCollectionExtensions.cs

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System;
2+
using System.Collections.Generic;
23
using System.Linq;
34
using System.Reflection;
45
using Microsoft.Extensions.DependencyInjection;
@@ -13,11 +14,14 @@ public static IServiceCollection AddAuthorizationChecker(this IServiceCollection
1314
services.AddOptions();
1415
services.AddScoped<IAuthorizationChecker, AuthorizationChecker>();
1516

16-
var voterTypes = Assembly.GetCallingAssembly().GetTypes().Where(type => type.GetInterfaces().Contains(typeof(IVoter)) && type.IsClass && !type.IsAbstract);
17+
var voterTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(LoadTypes).Where(type => typeof(IVoter).IsAssignableFrom(type) && type.IsClass && type.IsPublic && !type.IsAbstract);
1718

1819
foreach (var voterType in voterTypes)
1920
{
20-
services.AddTransient(voterType.GetInterfaces().First(type => type.IsGenericType), voterType);
21+
foreach (var voterInterface in voterType.GetInterfaces().Where(type => type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IVoter<>)))
22+
{
23+
services.AddTransient(voterInterface, voterType);
24+
}
2125
}
2226

2327
if (setupOptions != null)
@@ -27,5 +31,17 @@ public static IServiceCollection AddAuthorizationChecker(this IServiceCollection
2731

2832
return services;
2933
}
34+
35+
private static IEnumerable<Type> LoadTypes(Assembly assembly)
36+
{
37+
try
38+
{
39+
return assembly.GetTypes();
40+
}
41+
catch (ReflectionTypeLoadException reflectionTypeLoadException)
42+
{
43+
return reflectionTypeLoadException.Types.Where(type => type != null);
44+
}
45+
}
3046
}
3147
}

Directory.Build.props

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
</PropertyGroup>
1010

1111
<PropertyGroup>
12-
<PackageVersion>1.0.0</PackageVersion>
12+
<PackageVersion>1.0.1</PackageVersion>
1313
<Company>SharpGrip</Company>
1414
<Authors>SharpGrip</Authors>
1515
<Copyright>SharpGrip</Copyright>

0 commit comments

Comments
 (0)