From 0fc7c82321991270d0c666355648dfe23dff7eac Mon Sep 17 00:00:00 2001 From: Mike Bierlee Date: Sun, 18 Dec 2016 02:16:26 +0100 Subject: [PATCH] Add post-constructor/pre-destructor example --- .travis.yml | 1 + dub.json | 12 +++++ example/postconstructorpredestructor/app.d | 53 ++++++++++++++++++++++ 3 files changed, 66 insertions(+) create mode 100644 example/postconstructorpredestructor/app.d diff --git a/.travis.yml b/.travis.yml index 8ba3c70..fed7644 100644 --- a/.travis.yml +++ b/.travis.yml @@ -26,3 +26,4 @@ script: - dub build --build=release --config=registerOnResolveExample - dub build --build=release --config=constructorInjectionExample - dub build --build=release --config=valueInjectionExample + - dub build --build=release --config=postConstructorPreDestructorExample diff --git a/dub.json b/dub.json index 6b0f629..7cc781e 100644 --- a/dub.json +++ b/dub.json @@ -122,6 +122,18 @@ "importPaths": [ "source" ] + }, + { + "name" : "postConstructorPreDestructorExample", + "description" : "Example where the usage of post-constructors and pre-destructors are demonstrated.", + "targetType": "executable", + "targetName": "postConstructorPreDestructorExample", + "sourcePaths": [ + "example/postconstructorpredestructor" + ], + "importPaths": [ + "source" + ] } ] } diff --git a/example/postconstructorpredestructor/app.d b/example/postconstructorpredestructor/app.d new file mode 100644 index 0000000..32cc8b1 --- /dev/null +++ b/example/postconstructorpredestructor/app.d @@ -0,0 +1,53 @@ +/** + * Poodinis Dependency Injection Framework + * Copyright 2014-2016 Mike Bierlee + * This software is licensed under the terms of the MIT license. + * The full terms of the license can be found in the LICENSE file. + */ + +import poodinis; + +import std.stdio; + +class ADependency { + @PostConstruct + public void postConstructor() { + writeln("The dependency is created."); + } + + public void callMe() { + writeln("The dependency was called."); + } +} + +class AClass { + @Autowire + public ADependency dependency; // Dependencies are autowired before the post-constructor is called. + + @PostConstruct + public void postConstructor() { + writeln("The class is created."); + if (dependency !is null) { + writeln("The dependency is autowired."); + } else { + writeln("The dependency was NOT autowired."); + } + } + + @PreDestroy + public void preDestructor() { + writeln("The class is no longer registered with the container."); + } +} + +public void main() { + auto container = new shared DependencyContainer(); + container.register!ADependency; + container.register!AClass; + auto instance = container.resolve!AClass; // Will cause the post constructor to be called. + container.removeRegistration!AClass; // Will cause the pre destructor to be called. + + // The instance won't be destroyed by the container and as long as there are references to it, + // it will not be collected by the garbage collector either. + instance.dependency.callMe(); +}