diff --git a/LightweightIocContainer/Registrations/RegistrationBase.cs b/LightweightIocContainer/Registrations/RegistrationBase.cs index 7a43160..e1cffe8 100644 --- a/LightweightIocContainer/Registrations/RegistrationBase.cs +++ b/LightweightIocContainer/Registrations/RegistrationBase.cs @@ -111,8 +111,9 @@ namespace LightweightIocContainer.Registrations public IRegistrationBase WithFactory() { TypedFactory factory = new(_container); - Factory = factory; + + ValidateFactory(); _container.RegisterFactory(factory); return this; @@ -127,9 +128,17 @@ namespace LightweightIocContainer.Registrations public IRegistrationBase WithFactory() where TFactoryImplementation : TFactoryInterface { Factory = new CustomTypedFactory(); + ValidateFactory(); + _container.Register(); return this; } + + private void ValidateFactory() + { + if (Factory?.CreateMethods.Any(c => c.ReturnType == InterfaceType) != true) + throw new InvalidFactoryRegistrationException($"No create method that can create {InterfaceType}."); + } } } \ No newline at end of file diff --git a/Test.LightweightIocContainer/FluentFactoryRegistrationTest.cs b/Test.LightweightIocContainer/FluentFactoryRegistrationTest.cs index d9b6733..efb88a0 100644 --- a/Test.LightweightIocContainer/FluentFactoryRegistrationTest.cs +++ b/Test.LightweightIocContainer/FluentFactoryRegistrationTest.cs @@ -78,6 +78,12 @@ namespace Test.LightweightIocContainer public void ClearMultitonInstance() => throw new System.NotImplementedException(); } + [UsedImplicitly] + public interface ITestFactoryWrongReturn + { + public MultitonScope Create(); + } + public class MultitonScope { @@ -225,5 +231,9 @@ namespace Test.LightweightIocContainer Assert.AreNotSame(resolvedTest2, resolvedTest4); Assert.AreNotSame(resolvedTest3, resolvedTest5); } + + [Test] + public void TestInvalidCreateMethodReturnType() => + Assert.Throws(() => _iocContainer.Register().WithFactory()); } } \ No newline at end of file