Allow registration by interfaces

This commit is contained in:
Mike Bierlee 2014-05-16 00:22:26 +02:00
parent 6fb34bb233
commit 535f5df482
2 changed files with 33 additions and 7 deletions

View file

@ -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;
}

View file

@ -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");
}
}