- add factory validation

pull/57/head
Simon G 4 years ago
parent 39b18afb5d
commit 19fb3b1d0f
  1. 11
      LightweightIocContainer/Registrations/RegistrationBase.cs
  2. 10
      Test.LightweightIocContainer/FluentFactoryRegistrationTest.cs

@ -111,8 +111,9 @@ namespace LightweightIocContainer.Registrations
public IRegistrationBase WithFactory<TFactory>() public IRegistrationBase WithFactory<TFactory>()
{ {
TypedFactory<TFactory> factory = new(_container); TypedFactory<TFactory> factory = new(_container);
Factory = factory; Factory = factory;
ValidateFactory();
_container.RegisterFactory(factory); _container.RegisterFactory(factory);
return this; return this;
@ -127,9 +128,17 @@ namespace LightweightIocContainer.Registrations
public IRegistrationBase WithFactory<TFactoryInterface, TFactoryImplementation>() where TFactoryImplementation : TFactoryInterface public IRegistrationBase WithFactory<TFactoryInterface, TFactoryImplementation>() where TFactoryImplementation : TFactoryInterface
{ {
Factory = new CustomTypedFactory<TFactoryInterface>(); Factory = new CustomTypedFactory<TFactoryInterface>();
ValidateFactory();
_container.Register<TFactoryInterface, TFactoryImplementation>(); _container.Register<TFactoryInterface, TFactoryImplementation>();
return this; return this;
} }
private void ValidateFactory()
{
if (Factory?.CreateMethods.Any(c => c.ReturnType == InterfaceType) != true)
throw new InvalidFactoryRegistrationException($"No create method that can create {InterfaceType}.");
}
} }
} }

@ -78,6 +78,12 @@ namespace Test.LightweightIocContainer
public void ClearMultitonInstance<T>() => throw new System.NotImplementedException(); public void ClearMultitonInstance<T>() => throw new System.NotImplementedException();
} }
[UsedImplicitly]
public interface ITestFactoryWrongReturn
{
public MultitonScope Create();
}
public class MultitonScope public class MultitonScope
{ {
@ -225,5 +231,9 @@ namespace Test.LightweightIocContainer
Assert.AreNotSame(resolvedTest2, resolvedTest4); Assert.AreNotSame(resolvedTest2, resolvedTest4);
Assert.AreNotSame(resolvedTest3, resolvedTest5); Assert.AreNotSame(resolvedTest3, resolvedTest5);
} }
[Test]
public void TestInvalidCreateMethodReturnType() =>
Assert.Throws<InvalidFactoryRegistrationException>(() => _iocContainer.Register<ITest, Test>().WithFactory<ITestFactoryWrongReturn>());
} }
} }
Loading…
Cancel
Save