poodinis/example/postconstructorpredestructor/app.d

56 lines
1.6 KiB
D
Raw Normal View History

2017-02-13 20:20:35 +01:00
/**
* Poodinis Dependency Injection Framework
2023-01-11 00:01:51 +01:00
* Copyright 2014-2023 Mike Bierlee
2017-02-13 20:20:35 +01:00
* 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() {
2017-02-13 20:20:35 +01:00
writeln("The dependency is created.");
}
public void callMe() {
2017-02-13 20:20:35 +01:00
writeln("The dependency was called.");
}
}
class AClass {
@Autowire public ADependency dependency; // Dependencies are autowired before the post-constructor is called.
2017-02-13 20:20:35 +01:00
@PostConstruct public void postConstructor() {
2017-02-13 20:20:35 +01:00
writeln("The class is created.");
if (dependency !is null) {
2017-02-13 20:20:35 +01:00
writeln("The dependency is autowired.");
} else {
2017-02-13 20:20:35 +01:00
writeln("The dependency was NOT autowired.");
}
}
@PreDestroy public void preDestructor() {
2017-02-13 20:20:35 +01:00
writeln("The class is no longer registered with the container.");
}
}
public void main() {
2017-02-13 20:20:35 +01:00
auto container = new shared DependencyContainer();
2020-02-26 09:14:12 +01:00
container.register!(ADependency).onConstructed((Object obj) {
writeln("ADependency constructed");
});
container.register!(AClass).onConstructed((Object obj) {
writeln("AClass constructed");
});
2017-02-13 20:20:35 +01:00
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();
}