mirror of
https://github.com/mbierlee/poodinis.git
synced 2024-11-15 04:04:01 +01:00
Allow registration by interfaces
This commit is contained in:
parent
6fb34bb233
commit
535f5df482
|
@ -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;
|
||||
}
|
||||
|
|
|
@ -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");
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue