Skip to content

Commit

Permalink
Also include open generic types in registration. Closes #42
Browse files Browse the repository at this point in the history
  • Loading branch information
khellang committed Feb 27, 2018
1 parent 9b30ee2 commit f2bd7d7
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 8 deletions.
35 changes: 30 additions & 5 deletions src/Scrutor/ReflectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,6 @@ public static bool IsNonAbstractClass(this Type type, bool publicOnly)

if (typeInfo.IsClass && !typeInfo.IsAbstract)
{
if (typeInfo.IsGenericType && typeInfo.ContainsGenericParameters)
{
return false;
}

if (publicOnly)
{
return typeInfo.IsPublic || typeInfo.IsNestedPublic;
Expand Down Expand Up @@ -245,5 +240,35 @@ public static bool IsOpenGeneric(this Type type)
{
return type.GetTypeInfo().IsGenericTypeDefinition;
}

public static bool HasMatchingGenericArity(this Type interfaceType, TypeInfo typeInfo)
{
if (typeInfo.IsGenericType)
{
if (interfaceType.IsGenericType())
{
var argumentCount = interfaceType.GenericTypeArguments.Length;
var parameterCount = typeInfo.GenericTypeParameters.Length;

return argumentCount == parameterCount;
}
}

return true;
}

public static Type GetRegistrationType(this Type interfaceType, TypeInfo typeInfo)
{
if (typeInfo.IsGenericTypeDefinition)
{
if (interfaceType.IsGenericType())
{
return interfaceType.GetGenericTypeDefinition();
}
}

return interfaceType;
}

}
}
4 changes: 3 additions & 1 deletion src/Scrutor/ServiceTypeSelector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@ public ILifetimeSelector As(IEnumerable<Type> types)

public ILifetimeSelector AsImplementedInterfaces()
{
return AsTypeInfo(t => t.ImplementedInterfaces);
return AsTypeInfo(t => t.ImplementedInterfaces
.Where(x => x.HasMatchingGenericArity(t))
.Select(x => x.GetRegistrationType(t)));
}

public ILifetimeSelector AsMatchingInterface()
Expand Down
4 changes: 2 additions & 2 deletions test/Scrutor.Tests/ScanningTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ public void AutoRegisterAsMatchingInterface()
.AsMatchingInterface()
.WithTransientLifetime());

Assert.Equal(3, Collection.Count);
Assert.Equal(6, Collection.Count);

var services = Collection.GetDescriptors<ITransientService>();

Expand All @@ -333,7 +333,7 @@ public void AutoRegisterAsMatchingInterfaceSameNamespaceOnly()
.AsMatchingInterface((t, x) => x.InNamespaces(t.Namespace))
.WithTransientLifetime());

Assert.Equal(2, Collection.Count);
Assert.Equal(5, Collection.Count);

var service = Collection.GetDescriptor<ITransientService>();

Expand Down

0 comments on commit f2bd7d7

Please sign in to comment.