SimpleContainer

A simple implementation of Container.

SimpleContainer stores providers keyed by the TypeInfo and name, in that order. The container itself is registered, so that it can be injected as a dependency into other objects.

class SimpleContainer : Container {}

Inherited Members

From Container

addProvider
void addProvider(TypeInfo type, Provider provider)
void addProvider(TypeInfo type, string name, Provider provider)

Register a Provider for it's TypeInfo. A name can also be provided to disambiguate when multiple providers are needed

value
void value(string name, T value)
void value(T value)

Register a single value.

register
void register(Flag!"asSingleton" asSingleton = Yes.asSingleton)
void register(string name, Flag!"asSingleton" asSingleton = Yes.asSingleton)

Register a Class.

factory
void factory(Flag!"asSingleton" asSingleton = Yes.asSingleton)
void factory(string name, Flag!"asSingleton" asSingleton = Yes.asSingleton)
void factory(F func, Flag!"asSingleton" asSingleton = Yes.asSingleton)
void factory(string name, F func, Flag!"asSingleton" asSingleton = Yes.asSingleton)

Register a factory function for a type.

provider
void provider(Provider provider)
void provider(string name, Provider provider)

Register a provider using the type returned by provider.providedType.

Examples

1 import injected.injection;
2 
3 @Injectable!(int, Injected!(int, "a"))
4 static class A {
5     int x;
6     int y;
7     this(int x, int y) {
8         this.x = x;
9         this.y = y;
10     }
11 }
12 static class B : A  {
13     string name;
14     this(int x, int y, string name) {
15         super(x, y);
16         this.name = name;
17     }
18 }
19 static struct C {
20     string name;
21     ushort id;
22     static ushort idCounter = 0;
23 }
24 static C makeC() {
25     return C("Foo", C.idCounter++);
26 }
27 auto container = makeContainer();
28 container.value!int(0);
29 container.value!int("a", 1);
30 container.register!A();
31 container.register!(A, B)("b");
32 container.factory!string(delegate(C c) {
33     return c.name;
34 });
35 container.factory!(C, makeC)();
36 container.factory!(C, makeC)("c", No.asSingleton);
37 
38 assert(container.resolve!int() == 0);
39 assert(container.resolve!int("a") == 1);
40 assert(container.resolve!string() == "Foo");
41 auto a = container.resolve!A();
42 assert(a.x == 0);
43 assert(a.y == 1);
44 auto b = cast(B) container.resolve!A("b");
45 assert(b);
46 assert(b.x == 0);
47 assert(b.y == 0);
48 assert(b.name == "Foo");
49 assert(container.resolve!C().id == 0);
50 auto c = container.resolve!C("c");
51 assert(c.name == "Foo");
52 assert(c.id == 1);
53 assert(container.resolve!C("c").id == 2);

Meta