| 
 | 1 | +"""Mail service and user registration DI container example."""  | 
 | 2 | + | 
 | 3 | +from dependency_injector.containers import DeclarativeContainer  | 
 | 4 | +from dependency_injector.providers import Callable, Singleton  | 
 | 5 | + | 
 | 6 | +import example  | 
 | 7 | + | 
 | 8 | + | 
 | 9 | +class Container(DeclarativeContainer):  | 
 | 10 | + """DI container."""  | 
 | 11 | + | 
 | 12 | + mail_service = Singleton(example.MailService,  | 
 | 13 | + host='localhost',  | 
 | 14 | + port=587,  | 
 | 15 | + login='my_login',  | 
 | 16 | + password='super_secret_password')  | 
 | 17 | + | 
 | 18 | + add_user = Callable(example.add_user,  | 
 | 19 | + mailer=mail_service)  | 
 | 20 | + | 
 | 21 | + | 
 | 22 | +if __name__ == '__main__':  | 
 | 23 | + print('Using real mail service:')  | 
 | 24 | + Container.add_user('sample@mail.com', 'password')  | 
 | 25 | + # Using real mail service:  | 
 | 26 | + # Connecting server localhost:587 with my_login:super_secret_password  | 
 | 27 | + # Sending "Your password is password" to "sample@mail.com"  | 
 | 28 | + | 
 | 29 | + print('Using mail service stub:')  | 
 | 30 | + Container.add_user('sample@mail.com', 'password',  | 
 | 31 | + mailer=example.MailServiceStub())  | 
 | 32 | + # Using mail service stub:  | 
 | 33 | + # Emulating sending "Your password is password" to "sample@mail.com"  | 
 | 34 | + | 
 | 35 | + # Also you can override provider by another provider:  | 
 | 36 | + Container.mail_service.override(Singleton(example.MailServiceStub))  | 
 | 37 | + print('Using mail service stub by overriding mail service provider:')  | 
 | 38 | + Container.add_user('sample@mail.com', 'password')  | 
 | 39 | + # Using mail service stub by overriding mail service provider:  | 
 | 40 | + # Emulating sending "Your password is password" to "sample@mail.com"  | 
 | 41 | + Container.mail_service.reset_override() # Resetting provider overriding  | 
0 commit comments