diff --git a/source/poodinis/container.d b/source/poodinis/container.d index da5fbb4..e0b8ed6 100644 --- a/source/poodinis/container.d +++ b/source/poodinis/container.d @@ -1,22 +1,27 @@ module poodinis.container; struct Registration { - TypeInfo_Class registratedType = null; + TypeInfo registratedType = null; + TypeInfo_Class instantiatableType = null; public Object getInstance() { - return registratedType.create(); + return instantiatableType.create(); } } class Container { - private static Registration[TypeInfo_Class] registrations; + private static Registration[TypeInfo] registrations; private this() { } - public static Registration register(ClassType)() { - Registration newRegistration = { typeid(ClassType) }; + public static Registration register(ConcreteType)() { + return register!(ConcreteType, ConcreteType)(); + } + + public static Registration register(InterfaceType, ConcreteType)() { + Registration newRegistration = { typeid(InterfaceType), typeid(ConcreteType) }; registrations[newRegistration.registratedType] = newRegistration; return newRegistration; } diff --git a/test/poodinis/containertest.d b/test/poodinis/containertest.d index ac86cfb..59cfbda 100644 --- a/test/poodinis/containertest.d +++ b/test/poodinis/containertest.d @@ -3,7 +3,13 @@ import poodinis.container; import std.stdio; version(unittest) { - class TestClass { + interface TestInterface { + } + + class TestClass : TestInterface { + } + + class UnrelatedClass{ } unittest { @@ -17,6 +23,21 @@ version(unittest) { Container.register!(TestClass)(); TestClass actualInstance = Container.resolve!(TestClass)(); assert(actualInstance !is null, "Resolved type is null"); - assert(typeid(actualInstance) == typeid(TestClass), "Resolved class is not the same type as expected"); + assert(cast(TestClass) actualInstance, "Resolved class is not the same type as expected"); + } + + unittest { + // Test register interface + Container.register!(TestInterface, TestClass)(); + TestInterface actualInstance = Container.resolve!(TestInterface)(); + assert(actualInstance !is null, "Resolved type is null"); + assert(cast(TestInterface) actualInstance, "Resolved class is not the same type as expected"); + } + + unittest { + // Test resolve type registered with unrelated type fails + Container.register!(UnrelatedClass, TestClass)(); + UnrelatedClass actualInstance = Container.resolve!(UnrelatedClass)(); + assert(actualInstance is null, "Resolved type is not null"); } } \ No newline at end of file