poodinis/example/constructorinjection/app.d

66 lines
1.7 KiB
D
Raw Normal View History

2017-02-13 20:20:35 +01:00
/**
* Poodinis Dependency Injection Framework
2021-01-04 00:04:20 +01:00
* Copyright 2014-2021 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.
*/
2021-04-28 23:30:12 +02:00
import std.stdio;
2017-02-13 20:20:35 +01:00
class Scheduler {
private Calendar calendar;
// All parameters will autmatically be assigned when Scheduler is created.
this(Calendar calendar) {
this.calendar = calendar;
}
public void scheduleJob() {
calendar.findOpenDate();
}
}
class Calendar {
private HardwareClock hardwareClock;
// This constructor contains built-in type "int" and thus will not be used.
this(int initialDateTimeStamp, HardwareClock hardwareClock) {
}
// This constructor is chosen instead as candidate for injection when Calendar is created.
this(HardwareClock hardwareClock) {
this.hardwareClock = hardwareClock;
}
public void findOpenDate() {
hardwareClock.doThings();
}
}
class HardwareClock {
// Parameterless constructors will halt any further selection of constructors.
2021-04-28 23:30:12 +02:00
this() {}
2020-02-09 16:46:06 +01:00
2017-02-13 20:20:35 +01:00
// As a result, this constructor will not be used when HardwareClock is created.
this(Calendar calendar) {
throw new Exception("This constructor should not be used by Poodinis");
}
public void doThings() {
writeln("Things are being done!");
}
}
void main() {
import poodinis; // Locally imported to emphasize that classes do not depend on Poodinis.
auto dependencies = new shared DependencyContainer();
dependencies.register!Scheduler;
dependencies.register!Calendar;
2021-04-28 23:30:12 +02:00
dependencies.register!HardwareClock;
2017-02-13 20:20:35 +01:00
auto scheduler = dependencies.resolve!Scheduler;
scheduler.scheduleJob();
}