1 module tests.basic_register; 2 3 import std.stdio; 4 5 import unit_threaded; 6 7 import tests.utils; 8 import endovena; 9 10 interface IService { } 11 12 class SomeService: IService { } 13 14 interface IClient { 15 @property IService service(); 16 } 17 18 class SomeClient: IClient { 19 public this(IService service) { 20 _service = service; 21 } 22 private IService _service; 23 @property IService service() { return _service; } 24 } 25 26 @UnitTest 27 void register_as_types() { 28 Container container = new Container; 29 30 container.register!(IService, SomeService)(); 31 container.register!(IClient, SomeClient)(); 32 auto client = container.get!IClient(); 33 client.shouldNotBeNull; 34 client 35 .instanceof!SomeClient 36 .shouldBeTrue; 37 38 client.service 39 .instanceof!SomeService 40 .shouldBeTrue; 41 } 42 43 @UnitTest 44 void register_client_with_factory_delegate() { 45 Container container = new Container; 46 container.register!IClient(r => new SomeClient(r.get!IService())); 47 container.register!(IService, Singleton)(r => new SomeService()); 48 49 auto client = container.get!IClient(); 50 client.shouldNotBeNull; 51 52 client 53 .instanceof!SomeClient 54 .shouldBeTrue; 55 56 client.service 57 .instanceof!SomeService 58 .shouldBeTrue; 59 60 IService s1 = container.get!IService; 61 IService s2 = container.get!IService; 62 shouldBeTrue(s1 is s2); 63 } 64 65 @UnitTest 66 void specify_how_to_reuse_resolved_objects() { 67 Container container = new Container(); 68 69 /* 70 *Transient reuse means no reuse at all. 71 *Every time client is resolved/injected a new object will be created. 72 */ 73 container.register!(IClient, SomeClient, Transient)(); 74 75 /* 76 * You can omit reuse parameter when registering Transient objects. 77 *container.register!(IClient, SomeClient, Reuse.Transient)(); 78 */ 79 80 /* 81 *Singleton means that service object will be created at first resolve/injection, 82 *then the same instance will be returned for all subsequent resolves from this container. 83 */ 84 container.register!(IService, SomeService, Singleton)(); 85 86 auto client = container.get!(IClient); 87 auto anotherClient = container.get!(IClient); 88 89 assert(client !is anotherClient); 90 assert(client.service is anotherClient.service); 91 }