2023-03-06 23:29:28 +01:00
|
|
|
/**
|
|
|
|
* Poodinis Dependency Injection Framework
|
2024-02-17 13:08:59 +01:00
|
|
|
* Copyright 2014-2024 Mike Bierlee
|
2023-03-06 23:29:28 +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 {
|
2023-05-17 23:03:02 +02:00
|
|
|
@PostConstruct void postConstructor() {
|
2023-03-06 23:29:28 +01:00
|
|
|
writeln("The dependency is created.");
|
|
|
|
}
|
|
|
|
|
2023-05-17 23:03:02 +02:00
|
|
|
void callMe() {
|
2023-03-06 23:29:28 +01:00
|
|
|
writeln("The dependency was called.");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class AClass {
|
2023-05-17 23:03:02 +02:00
|
|
|
@Inject ADependency dependency; // Dependencies are autowired before the post-constructor is called.
|
2023-03-06 23:29:28 +01:00
|
|
|
|
2023-05-17 23:03:02 +02:00
|
|
|
@PostConstruct void postConstructor() {
|
2023-03-06 23:29:28 +01:00
|
|
|
writeln("The class is created.");
|
|
|
|
if (dependency !is null) {
|
|
|
|
writeln("The dependency is autowired.");
|
|
|
|
} else {
|
|
|
|
writeln("The dependency was NOT autowired.");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-17 23:03:02 +02:00
|
|
|
@PreDestroy void preDestructor() {
|
2023-03-06 23:29:28 +01:00
|
|
|
writeln("The class is no longer registered with the container.");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-17 23:03:02 +02:00
|
|
|
void main() {
|
2023-03-06 23:29:28 +01:00
|
|
|
auto container = new shared DependencyContainer();
|
|
|
|
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.
|
|
|
|
|
|
|
|
// 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();
|
|
|
|
}
|