From cc104b95ece0b93c4b77a48e5c798e0285304743 Mon Sep 17 00:00:00 2001 From: "Simon G." Date: Thu, 19 Dec 2024 13:03:06 +0100 Subject: [PATCH] - fix validation of open generic type registrations without parameter constraints --- .../IocValidator.cs | 9 +++++-- .../IocValidatorTest.cs | 26 +++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/LightweightIocContainer.Validation/IocValidator.cs b/LightweightIocContainer.Validation/IocValidator.cs index c4b7bb2..a0d44c8 100644 --- a/LightweightIocContainer.Validation/IocValidator.cs +++ b/LightweightIocContainer.Validation/IocValidator.cs @@ -68,8 +68,13 @@ private void TryResolve(Type type, object?[]? arguments, List validat foreach (Type genericArgument in genericArguments.Where(g => g.IsGenericParameter)) { Type[] genericParameterConstraints = genericArgument.GetGenericParameterConstraints(); - object mock = Substitute.For(genericParameterConstraints, []); - genericParameters.Add(mock.GetType()); + if (genericParameterConstraints.Any()) + { + object mock = Substitute.For(genericParameterConstraints, []); + genericParameters.Add(mock.GetType()); + } + else + genericParameters.Add(typeof(object)); } type = type.MakeGenericType(genericParameters.ToArray()); diff --git a/Test.LightweightIocContainer.Validation/IocValidatorTest.cs b/Test.LightweightIocContainer.Validation/IocValidatorTest.cs index 4fcf85f..02a9038 100644 --- a/Test.LightweightIocContainer.Validation/IocValidatorTest.cs +++ b/Test.LightweightIocContainer.Validation/IocValidatorTest.cs @@ -41,6 +41,12 @@ public class Constraint : IConstraint; [UsedImplicitly] public class GenericTest : IGenericTest where T : IConstraint, new(); + [UsedImplicitly] + public interface IGenericTestWithoutConstraint; + + [UsedImplicitly] + public class GenericTestWithoutConstraint : IGenericTestWithoutConstraint; + [UsedImplicitly] public interface IGenericTestFactory { @@ -58,6 +64,15 @@ public GenericParameter(IGenericTest test) } } + + [UsedImplicitly] + public class GenericParameterWithoutConstraint : IGenericParameter + { + public GenericParameterWithoutConstraint(IGenericTestWithoutConstraint test) + { + + } + } [UsedImplicitly] private class TestViewModelDontIgnoreDesignTimeCtor : ITest @@ -321,6 +336,17 @@ public void TestValidateOpenGenericTypeAsParameter() IocValidator validator = new(iocContainer); validator.Validate(); } + + [Test] + public void TestValidateOpenGenericTypeWithoutConstraintAsParameter() + { + IocContainer iocContainer = new(); + iocContainer.Register(r => r.AddOpenGenerics(typeof(IGenericTestWithoutConstraint<>), typeof(GenericTestWithoutConstraint<>))); + iocContainer.Register(r => r.Add()); + + IocValidator validator = new(iocContainer); + validator.Validate(); + } private void AssertNoMatchingConstructorFoundForType(AggregateException aggregateException) {