Last active
December 20, 2015 19:49
-
-
Save alecthomas/6185948 to your computer and use it in GitHub Desktop.
Example of using Injector with DI coupling to application-level classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from injector import Module, Injector, provides, inject, singleton | |
from some_credit_card_provider import CreditCardConnection, CreditCardVendor | |
@singleton | |
class CreditCardProcessor(object): | |
@inject(vendor=CreditCardVendor, connection=CreditCardConnection) | |
def __init__(self, vendor, connection): | |
self.vendor = vendor | |
self.connection = connection | |
def charge_order(self, card, amount): | |
self.connection.charge_order(self.vendor, card, amount) | |
@singleton | |
class TransactionLog(object): | |
def __init__(self): | |
self.log = [] | |
def log_order(self, user, amount): | |
self.log.append((user, amount)) | |
@singleton | |
class BillingService(object): | |
@inject(credit_card_processor=CreditCardProcessor, transaction_log=TransactionLog) | |
def __init__(self, credit_card_processor, transaction_log): | |
self.credit_card_processor = credit_card_processor | |
self.transaction_log = transaction_log | |
def charge_order(self, order, credit_card): | |
self.credit_card_processor.charge_order() | |
class Cart(object): | |
@inject(billing_service=BillingService) | |
def __init__(self, billing_service): | |
self.billing_service = billing_service | |
self.order = [] | |
def add(self, item): | |
self.order.append(item) | |
def checkout(self, credit_card): | |
self.billing_service.charge_order(self.order, credit_card) | |
class ShoppingModule(Module): | |
def __init__(self, vendor_id): | |
self.vendor_id = vendor_id | |
@provides(CreditCardConnection, scope=singleton) | |
def provide_credit_card_connection(self): | |
return CreditCardConnection() | |
@provides(CreditCardVendor, scope=singleton) | |
def provide_vendor(self): | |
return CreditCardVendor(self.vendor_id) | |
def main(): | |
injector = Injector([ShoppingModule('my_vendor_id')]) | |
cart = injector.get(Cart) | |
cart.add('some item') | |
cart.add('some other item') | |
cart.checkout('xxxx xxxx xxxx xxxx') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment