- fix validation of open generic type registrations without parameter constraints

master
Simon G. 12 months ago
parent 1b84c307d4
commit cc104b95ec
Signed by: SimonG
GPG Key ID: 0B82B964BA536523
  1. 5
      LightweightIocContainer.Validation/IocValidator.cs
  2. 26
      Test.LightweightIocContainer.Validation/IocValidatorTest.cs

@ -68,9 +68,14 @@ public class IocValidator(IocContainer iocContainer)
foreach (Type genericArgument in genericArguments.Where(g => g.IsGenericParameter)) foreach (Type genericArgument in genericArguments.Where(g => g.IsGenericParameter))
{ {
Type[] genericParameterConstraints = genericArgument.GetGenericParameterConstraints(); Type[] genericParameterConstraints = genericArgument.GetGenericParameterConstraints();
if (genericParameterConstraints.Any())
{
object mock = Substitute.For(genericParameterConstraints, []); object mock = Substitute.For(genericParameterConstraints, []);
genericParameters.Add(mock.GetType()); genericParameters.Add(mock.GetType());
} }
else
genericParameters.Add(typeof(object));
}
type = type.MakeGenericType(genericParameters.ToArray()); type = type.MakeGenericType(genericParameters.ToArray());
} }

@ -41,6 +41,12 @@ public class IocValidatorTest
[UsedImplicitly] [UsedImplicitly]
public class GenericTest<T> : IGenericTest<T> where T : IConstraint, new(); public class GenericTest<T> : IGenericTest<T> where T : IConstraint, new();
[UsedImplicitly]
public interface IGenericTestWithoutConstraint<T>;
[UsedImplicitly]
public class GenericTestWithoutConstraint<T> : IGenericTestWithoutConstraint<T>;
[UsedImplicitly] [UsedImplicitly]
public interface IGenericTestFactory public interface IGenericTestFactory
{ {
@ -59,6 +65,15 @@ public class IocValidatorTest
} }
} }
[UsedImplicitly]
public class GenericParameterWithoutConstraint : IGenericParameter
{
public GenericParameterWithoutConstraint(IGenericTestWithoutConstraint<IParameter> test)
{
}
}
[UsedImplicitly] [UsedImplicitly]
private class TestViewModelDontIgnoreDesignTimeCtor : ITest private class TestViewModelDontIgnoreDesignTimeCtor : ITest
{ {
@ -322,6 +337,17 @@ public class IocValidatorTest
validator.Validate(); validator.Validate();
} }
[Test]
public void TestValidateOpenGenericTypeWithoutConstraintAsParameter()
{
IocContainer iocContainer = new();
iocContainer.Register(r => r.AddOpenGenerics(typeof(IGenericTestWithoutConstraint<>), typeof(GenericTestWithoutConstraint<>)));
iocContainer.Register(r => r.Add<IGenericParameter, GenericParameterWithoutConstraint>());
IocValidator validator = new(iocContainer);
validator.Validate();
}
private void AssertNoMatchingConstructorFoundForType<T>(AggregateException aggregateException) private void AssertNoMatchingConstructorFoundForType<T>(AggregateException aggregateException)
{ {
Exception exception = aggregateException?.InnerExceptions[0]; Exception exception = aggregateException?.InnerExceptions[0];

Loading…
Cancel
Save