Add a constuction handler

This commit is contained in:
heromyth 2020-02-26 16:14:12 +08:00
parent 55726e84db
commit 3b11c4aec4
3 changed files with 24 additions and 3 deletions

View file

@ -42,8 +42,14 @@ class AClass {
public void main() {
auto container = new shared DependencyContainer();
container.register!ADependency;
container.register!AClass;
container.register!(ADependency).onConstructed((Object obj) {
writeln("ADependency constructed");
});
container.register!(AClass).onConstructed((Object obj) {
writeln("AClass constructed");
});
auto instance = container.resolve!AClass; // Will cause the post constructor to be called.
container.removeRegistration!AClass; // Will cause the pre destructor to be called.

View file

@ -22,6 +22,7 @@ import std.stdio;
alias CreatesSingleton = Flag!"CreatesSingleton";
alias InstanceFactoryMethod = Object delegate();
alias InstanceEventHandler = void delegate(Object instance);
class InstanceCreationException : Exception {
this(string message, string file = __FILE__, size_t line = __LINE__) {
@ -39,6 +40,7 @@ struct InstanceFactoryParameters {
class InstanceFactory {
private Object instance = null;
private InstanceFactoryParameters _factoryParameters;
private InstanceEventHandler _constructionHandler;
this() {
factoryParameters = InstanceFactoryParameters();
@ -75,9 +77,17 @@ class InstanceFactory {
}
instance = _factoryParameters.factoryMethod();
if(_constructionHandler !is null) {
_constructionHandler(instance);
}
return instance;
}
void onConstructed(InstanceEventHandler handler) {
_constructionHandler = handler;
}
private void printDebugUseExistingInstance() {
if (_factoryParameters.instanceType !is null) {
writeln(format("DEBUG: Existing instance returned of type %s", _factoryParameters.instanceType.toString()));

View file

@ -60,7 +60,6 @@ class Registration {
return linkedRegistration.getInstance(context);
}
if (instanceFactory is null) {
throw new InstanceCreationException("No instance factory defined for registration of type " ~ registeredType.toString());
}
@ -72,6 +71,12 @@ class Registration {
this.linkedRegistration = registration;
return this;
}
Registration onConstructed(InstanceEventHandler handler) {
if(instanceFactory !is null)
instanceFactory.onConstructed(handler);
return this;
}
}
/**